Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmake include header into every source file

Tags:

c++

c

cmake

I actually have a simple question, but couldn't find an answer. Maybe you can point me to a duplicate. So, the question is: is it possible to tell cmake to instruct a compiler to automatically include some header at the beginning of every source file, so there would be no need to put #include foo.h? Thanks!

like image 841
Andrei Chernikov Avatar asked Sep 25 '15 01:09

Andrei Chernikov


People also ask

How do I include a .h file in CMake?

To include headers in CMake targets, use the command target_include_directories(...) . Depending on the purpose of the included directories, you will need to define the scope specifier – either PUBLIC , PRIVATE or INTERFACE .

What does Include_directories do in CMake?

Add include directories to the build. Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory.

How do I add to CMake?

To add a library in CMake, use the add_library() command and specify which source files should make up the library. Rather than placing all of the source files in one directory, we can organize our project with one or more subdirectories. In this case, we will create a subdirectory specifically for our library.


1 Answers

CMake doesn't have a feature for this specific use case, but as you've hinted, compilers such as GCC have the -include flag which acts as if there was an #include "foo.h" in the source file, and since CMake can pass arguments to compilers, you can do it via add_definitions.

This answer covers what the flag is for GCC, Clang and MSVC which should cover a lot of bases. So in CMake, detect what the compiler is and pass the appropriate flag.

Here's what the CMake code might look like:

if(MSVC)
    add_definitions(/FI"foo.h")
else()
    # GCC or Clang
    add_definitions(-include foo.h)
endif()

Comments

In general, doing this is a bad idea. Code inspection tools (like IDEs, or doxygen) will be confused by it, not to mention other humans looking at the code. If not all source files actually require the definition, adding extra #includes will slow down compile time. If you actually do need the same header (and it's not a system header) in all your source files, it may be symptomatic of high coupling in your code. And for what benefit? Not having to add one line to your files?

However, it's necessary to note that compilers support this for a reason; there are a few weird edge cases (example 1, example 2) where it's a useful thing to do.

Just be aware that you're doing this for the right reasons.

like image 77
congusbongus Avatar answered Sep 28 '22 01:09

congusbongus