snorkel's blog

By snorkel, history, 3 years ago, In English

How can I include a header file without writing #include "header.h" for example using cmakelists.txt?

For example without writing #define DEFINE I defined it from cmakelists with the command add_definitions(-DDEFINE)

Can I do the similar thing?

  • Vote: I like it
  • +6
  • Vote: I do not like it

»
3 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Depends on the compiler. E.g. GCC has -include header.h key, see docs.

You can use it in CMakeLists.txt via add_compile_options, e.g. add_compile_options(-include header.h). Note that this will include header.h in each translation unit ("source file") for all targets.

  • »
    »
    3 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    This does not work for me. I tried both Cygwin and MinGW.

    • »
      »
      »
      3 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Make sure add_compile_options is specified before add_executable, like this.

      Alternatively, use target_compile_options(main PRIVATE -include pre-main.inc.cpp) after add_executable(main main.cpp).

      • »
        »
        »
        »
        3 years ago, # ^ |
        Rev. 3   Vote: I like it 0 Vote: I do not like it

        If I write it before add_executable it says header.h: No such file or directory. My Cmake looks like this:

        "untitled1" is the project name.

        cmake
        • »
          »
          »
          »
          »
          3 years ago, # ^ |
            Vote: I like it +1 Vote: I do not like it

          So did you try to think why it says 'No such file or directory' if the file exists? Maybe it doesn't know where to find the file? Try specifying the absolute path.

»
3 years ago, # |
  Vote: I like it +1 Vote: I do not like it

bump