Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include one header file in each source file

Tags:

c++

c

header

clang

Say you have 100s of source files (.c or .cpp) files, and you want to include some definitions, function/variable declarations in each of them. Normally in C/C++, you use header files for that purpose. But in this case you need to put #include "header.h" in each source file.

Now my question is, is there a way to include one header for all the files without putting #include "header.h" in each of the file, because it will be very tiresome to write #include "header.h" for 100s of source files.

like image 956
pythonic Avatar asked Mar 30 '12 14:03

pythonic


2 Answers

You could solve this problem using a unix pipe

find ./ -name "*.c" -or -name "*.cpp" | xargs -n 1 sed -i '1 i #include <my_header.h>'
like image 40
brice Avatar answered Oct 06 '22 01:10

brice


You can use the -include flag for clang or GCC. From the man page:

-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.

If multiple -include options are given, the files are included in the order they appear on the command line.

Example:

clang -include header.h -c file1.c
clang -include header.h -c file2.c
clang -include header.h -c file3.c
clang -o app file1.o file2.o file3.o

MSVC has the /FI flag, which is similar.

like image 142
Carl Norum Avatar answered Oct 06 '22 00:10

Carl Norum