使用 Makefile 在编译中排除源文件

是否可以在编译过程中使用 Makefile 中的通配符函数排除源文件?

比如有几个源文件,

src/foo.cpp
src/bar.cpp
src/...

在我的档案里,

SRC_FILES = $(wildcard src/*.cpp)

但我想排除 bar.cpp 这可能吗?

59666 次浏览

You can use Makefile subst function:

 EXCLUDE=$(subst src/bar.cpp,,${SRC_FILES})

use find for it :)

SRC_FILES := $(shell find src/ ! -name "bar.cpp" -name "*.cpp")

If you're using GNU Make, you can use filter-out:

SRC_FILES := $(wildcard src/*.cpp)
SRC_FILES := $(filter-out src/bar.cpp, $(SRC_FILES))

Or as one line:

SRC_FILES = $(filter-out src/bar.cpp, $(wildcard src/*.cpp))

The Unix glob pattern src/[!b]*.cpp excludes all src files that start with b.

That only would work, however, if bar.cpp is the only src file that starts with b or if you're willing to rename it to start with a unique character.

If you're trying to add that all into one call:

g++ -g $(filter-out excludedFile.cpp, $(wildcard *.cpp)) -o main where the normal one would be g++ -g *.cpp -o main

And if you want to run it as well:

g++ -g $(filter-out excludedFile.cpp, $(wildcard *.cpp)) -o main && ./main