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

时间:2012-03-20 12:54:28

标签: c++ makefile

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

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

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

我有一个“.c”的Makefile,但这似乎不起作用。它只是创建目标文件而不是实际链接它。它如下:

SRCS=$(wildcard *.c)
OBJS=(SRCS:.c=.o)
all: $(OBJS)

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

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

for i in ./*.cpp
do
   g++ -Wno-deprecated $i -o `basename $i .cpp`".exe"
done

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

4 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:3)

这是我使用的Makefile

CC = gcc
CFLAGS = -g -O2 -std=gnu99 -static -Wall -Wextra -Isrc -rdynamic -fomit-frame-pointer
all: $(patsubst %.c, %.out, $(wildcard *.c))
%.out: %.c Makefile
    $(CC) $(CFLAGS) $< -o $@ -lm
clean:
    rm *.out                      

你应该将它粘贴在家里的某个地方,每当你改变目录时,只需将它复制到那里。我在〜/ .basrc中使用别名来复制它

alias get_makefile_here='cp ~/Makefile ./'

只需按make和bam,即可完成。另请注意,一旦完成旧文件,它将无法重建其可执行文件。

答案 2 :(得分:1)

我的回答建立在@Haatschii

的答案之上

我不希望我的二进制文件具有.out前缀。我也使用他现有的Make语法来执行清理。

CXX=clang++
CXXFLAGS=-Wall -Werror -std=c++11

all: $(patsubst %.cpp, %.out, $(wildcard *.cpp))

%.out: %.cpp Makefile
        $(CXX) $(CXXFLAGS) $< -o $(@:.out=)

clean: $(patsubst %.cpp, %.clean, $(wildcard *.cpp))

%.clean:
        rm -f $(@:.clean=)

答案 3 :(得分:0)

您可以创建的最简单的makefile可能对您有用:

all: examp1.exe examp2.exe examp3.exe

这将使用make的默认规则来创建三个程序。

相关问题