0

I found that I can use:

add_definitions(-DFOO -DBAR ...)

Unfortunately this is not a portable solution. If I use gcc, it will understand the -D switch, but If I use another compiler it may not understand that switch.

Is there another solution such as

set(CMAKE_DEFINES ${CMAKE_DEFINES} FOO BAR)
nowox
  • 25,978
  • 39
  • 143
  • 293
  • The `-D` is parsed by CMake, so it is portable and should work on all platforms. Can you please add any error messages you may have encountered? – Florian Aug 24 '17 at 08:46
  • I had an error message with `add_definitions("-std=c99")` which is gcc specific. There is an equivalent in IAR, but CMake probably doesn't know it – nowox Aug 24 '17 at 09:21
  • Ok. Don't use `add_definitions()` for any other compiler switches then definitions. CMake has cross-platform abstraction/options for some compiler switches. What you are searching for is defined in a variable named [`CMAKE_C_STANDARD`](https://cmake.org/cmake/help/latest/variable/CMAKE_C_STANDARD.html). – Florian Aug 24 '17 at 09:32
  • Possible duplicate of [How to set language standard (-std) for Clang static analyzer in Qt Creator](https://stackoverflow.com/questions/39001501/how-to-set-language-standard-std-for-clang-static-analyzer-in-qt-creator) – Florian Aug 24 '17 at 09:32
  • I don't understand how it works then. In the function `add_definition` CMake will parse and recognize the content and eventually replace it with things such as `--flags-linker -DFFOO` for a SHARC compiler, but it doesn't know how to parse the `-std=c99`. How do I know which method I need to use? – nowox Aug 24 '17 at 09:35
  • That said adding `set(CMAKE_C_STANDARD 99)` doesn't do the trick for it. It doesn't add anything to my compiler at build time. – nowox Aug 24 '17 at 09:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/152725/discussion-between-nowox-and-florian). – nowox Aug 24 '17 at 09:48

1 Answers1

1

If set(CMAKE_C_STANDARD 99) does not work for all your compilers, then use the usual modern way of specifying compile options:

target_compile_options(mytarget PUBLIC -std=c99)

You can also add in compiler checks if necessary for different types of compiler.

Alternatively, you can directly modify the compiler flag variables, e.g. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=c99"), again with possible compiler checks.

If for some reason your compiler cannot even work or produce successful builds without a particular option, then look into pointing to include files for the variable CMAKE_USER_MAKE_RULES_OVERRIDE containing CMAKE_C_FLAGS_<CONFIG>_INIT variables for initial compiler flags per build/configuration type.

utopia
  • 1,477
  • 8
  • 7
  • Yeaah, yet a third option. CMake confuses me a lot. I feel very lost. It's been two days I am trying to look for a basic example and nothing works :( – nowox Aug 24 '17 at 12:16