Include one header file in each source file

后端 未结 4 543
心在旅途
心在旅途 2021-01-19 14:50

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 he

相关标签:
4条回答
  • 2021-01-19 15:31

    Yes, it would be tiresome. This is why you uses the shell...

    The following mystical incantation will do exactly what you ask in a few keystrokes!

    find ./ -name "*.c" -or -name "*.cpp" | xargs -n 1 sed -i '1 i #include <my_header.h>'
    

    Bow down to the mighty power of unix, heathens...

    0 讨论(0)
  • 2021-01-19 15:41

    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.

    0 讨论(0)
  • 2021-01-19 15:45

    Header files are not definitions - they are declarations.

    You put as few in as possible - saves the compiler work and also inter-dependencies.

    You can even reduce the number further by using forward declarations in those header files.

    If you are clever you can get you IDE to help you out with filling in the gaps instead of hurting your fingers.

    0 讨论(0)
  • 2021-01-19 15:49

    You can't do that, although you could write a script for you to do it. A script that takes each files, and writes #include "header.h" at top. Edit: -include in gcc does this.

    However, what you need is achievable in a different way through the compiler options. In gcc, with -D.

    Let's say, you want the define DEBUG_LEVEL to 2 in all your source files. You can simply do this by invoking gcc like this:

    gcc -DDEBUG_LEVEL=2
    

    Note that in this case, you would need to rebuild all your project (which would have been done anyway if you had changed this definition in 1 header file to which ALL the source files depend on)

    0 讨论(0)
提交回复
热议问题