在C++应用程序的makefile中包含一个C文件?

huangapple go评论74阅读模式
英文:

Include a C file in the makefile of a C++ application?

问题

你的问题可能是由于目标文件夹 "obj/" 不存在而导致的。确保在运行 make 命令之前,"obj/" 文件夹已经存在。

英文:

I'm trying to include a C library then compile it along with my C++ application but I can't get my makefile work properly:

SRC = main.cpp menu.cpp dialog_wnd.cpp player.cpp
C_SRC = miniaudio.c
CXX = g++ 
CXXFLAGS = -Wall $(shell fltk-config --cxxflags)

LFLAGS = $(shell fltk-config --ldflags)

OBJS = $(SRC:.cpp=.o) $(C_SRC:.c=.o)
DIR_OBJ = obj/
DIR_OBJS = $(addprefix $(DIR_OBJ), $(OBJS))

$(DIR_OBJ)%.o: %.cpp %.c *.h 
        $(CXX) $(CXXFLAGS) -c $(<) -o $(@)

EXE = myApplication

all: $(EXE)

$(EXE): $(DIR_OBJS)
        $(CXX) -o $@ $^ $(LFLAGS)

depend:
        makedepend -- $(CXXFLAGS) -- $(SRC) $(C_SRC)

strip: $(EXE)
        strip --strip-all $(EXE)

clean:
        rm -f $(DIR_OBJS)
        rm -f $(EXE)

I get this error:

> make: *** No rule to make target 'obj/main.o', needed by
> 'myApplication'.

What did I do wrong ?

答案1

得分: 1

$(DIR_OBJ)%.o: %.cpp %.c *.h会使每个目标文件都需要同时对应一个.cpp .c文件。

建议将其拆分为两部分,这样可以使用适当的编译器($(CC))来处理C代码。对于选项,可以使用CPPFLAGS,用于同时应用的选项,以及CFLAGS,用于由C编译器使用的标志。

示例:

CPPFLAGS = -Wall
CXXFLAGS = $(shell fltk-config --cxxflags)

$(DIR_OBJ)%.o: %.cpp *.h 
        $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@

$(DIR_OBJ)%.o: %.c *.h 
        $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@

注意:使每个目标文件依赖于每个头文件将在每次更改单个头文件时需要进行完全重建。

英文:

$(DIR_OBJ)%.o: %.cpp %.c *.h makes every object file require both a corresponding .cpp and .c file.

I suggest splitting it in two, which also makes it possible to use the proper compiler ($(CC)) for the C code. For the flags, use CPPFLAGS for options that you want both to use and CFLAGS for flags to be used by the C compiler.

Example:

CPPFLAGS = -Wall
CXXFLAGS = $(shell fltk-config --cxxflags)

$(DIR_OBJ)%.o: %.cpp *.h 
        $(CXX) $(CPPFLAGS) $(CXXFLAGS)-c $&lt; -o $@

$(DIR_OBJ)%.o: %.c *.h 
        $(CC) $(CPPFLAGS) $(CFLAGS) -c $&lt; -o $@

Note: Making each object file depend on every header file will require a full rebuild every time you touch a single header file.

huangapple
  • 本文由 发表于 2023年5月22日 19:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定