93

Is it possible to exclude a source file in the compilation process using wildcard function in a Makefile?

Like have several source files,

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

Then in my makefile I have,

SRC_FILES = $(wildcard src/*.cpp)

But I want to exclude the bar.cpp. Is this possible?

5 Answers 5

171

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))
3
18

use find for it :)

SRC_FILES := $(shell find src/ ! -name "bar.cpp" -name "*.cpp")
1
  • 1
    did you mean $(shell find src/ ... )? Commented Apr 23, 2012 at 7:45
7

You can use Makefile subst function:

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

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.

2
  • This works great when you also have to use .SECONDEXPANSION wildcard and pattern replacement such as locales/%/_bundle.ftl: $$(wildcard locales/%/[!_]*.ftl), Thanks!
    – zanona
    Commented Oct 2, 2020 at 7:33
  • @zanona, you're welcome! I'm glad you found it useful.
    – ma11hew28
    Commented Oct 2, 2020 at 20:06
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.