Reputation: 802
My current directory looks as follow:
root
|___src
| |
| |____Makefile
| |____a.cpp
| |____b.cpp
| |____c.h
| |____tests
| |
|______________|____test.cpp
Is there a way from the makefile to force all files under tests directory to include c.h
Upvotes: 1
Views: 800
Reputation: 99094
You haven't answered either of my questions, so I'll have to make some guesses.
This may be what you're looking for:
%.o: %.cpp
@$(CXX) -c $< -o $@
tests/%.o: tests/%.cpp
@$(CXX) -include c.h -c $< -o $@
EDIT:
If you want to insert #include "c.h"
at the top of a source file, you can use this sed command:
sed -i "" '1{h;s/.*/#include "c.h"/;G;}' filename
If you want to be sure you don't do so more than once, you can do this:
sed -i "" '1{h;s/.*/#include "c.h"/;G;s/\(.*\)\n\1$/\1/;}' filename
There are several different ways to do this with a makefile. Here is one crude-but-effective approach:
tests/%.o: tests/%.cpp
@sed -i "" '1{h;s/.*/#include "c.h"/;G;s/\(.*\)\n\1$/\1/;}' $<
@$(CXX) -c $< -o $@
But Make will work better if you run sed on each source file only once. This can be done, but it requires more careful thought about priorities.
Upvotes: 3
Reputation: 136208
gcc
and clang
support -include file
command line option.
-include file
Process file as if #include "file" appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory instead of the directory containing the main source file. If not found there, it is searched for in the remainder of the #include "..." search chain as normal.
Other compilers may have a similar option.
Upvotes: 0