Makefile将目录中的所有cpp文件编译成单独的可执行文件

kau*_*hik 8 c++ makefile

我现在正在学习C++.我想要一个makefile,它将编译当前目录中的所有cpp文件以分隔可执行文件.例如:

在一个目录中有3个c ++文件,例如examp1.cpp,examp2.cppexamp3.cpp.我想要一个makefile,它将编译并链接它们并提供examp1.exe,examp2.exeexamp3.exe

我已经创建了一个bash脚本来编译所有这些脚本并创建exes但我认为; 这不是确切的方法.

我有一个".c"的Makefile,但这似乎不适用于此.它只是创建目标文件而不是实际链接它.它如下:

SRCS=$(wildcard *.c)
OBJS=(SRCS:.c=.o)
all: $(OBJS)
Run Code Online (Sandbox Code Playgroud)

上面的代码将所有新的和修改过的".c"文件编译为当前目录中具有相同名称的".o"文件.

我用来创建可执行文件的bash脚本如下:

for i in ./*.cpp
do
   g++ -Wno-deprecated $i -o `basename $i .cpp`".exe"
done
Run Code Online (Sandbox Code Playgroud)

这意味着我想要放在那个目录中的任何".cpp"文件,使用简单的"make all"或者它应该编译的任何东西.

Haa*_*hii 17

一个最小的Makefile,你想做的是:

#Tell make to make one .out file for each .cpp file found in the current directory
all: $(patsubst %.cpp, %.out, $(wildcard *.cpp))

#Rule how to create arbitary .out files. 
#First state what is needed for them e.g. additional headers, .cpp files in an include folder...
#Then the command to create the .out file, probably you want to add further options to the g++ call.
%.out: %.cpp Makefile
    g++ $< -o $@ -std=c++0x
Run Code Online (Sandbox Code Playgroud)

你必须用你正在使用的编译器替换g ++,并可能调整一些特定于平台的设置,但Makefile本身应该可以工作.

  • 如果你复制和粘贴,你必须用一个标签替换"g ++"前面的for空格. (3认同)