0

I want to have globally included header in my C++ cmake project. E.g, I want to have lib included in every file in my project without having to put the #include <string> in every file

Mahashi
  • 119
  • 7
  • I think you can add some compiler specific source file properties to force an include but this is dependent on the compiler and you would have to iterate through the source files of the target to apply the properties. – drescherjm Jun 10 '21 at 13:46

1 Answers1

0

My answer would be: Don't do that. It will make your code much less portable, harder to read, harder to debug.

Headers can be a pain to deal with, but it is what is it until we have a modularized standard library.

What you could do though is to create a src/common/includes.h file containing all the stuff you want everywhere:

// includes.h
#include <string>
#include <vector>
#include <functional>
#include <unordered_map>
// ...

Add the include directory to your target:

target_include_directories(your-exe PUBLIC src/common)

Then, in every files, simply include it:

#include <includes.h>

There exist arguments that will change the compiler behaviour, but this is primarily to deal with precompiled header, which have requirements on the order of inclusion.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141