Difference between add_compile_options and SET (CMAKE_CXX_FLAGS ...)

This question is related to Have Cmake use CXX and CXXFLAGS while driving links? In the first question, we are trying to tell CMake to use CXXFLAGS when it invokes the linker.

add_compile_options

We found that the following code

 if (CMAKE_VERSION VERSION_LESS 2.8.12) add_definitions(-foo) else() add_compile_options(-foo) endif() message(STATUS, "CXXFLAGS: ${CMAKE_CXX_FLAGS}") 

outputs a conclusion

 CXXFLAGS: 

SET CMAKE_CXX_FLAGS

We found that the following code

 SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -foo" ) message(STATUS, "CXXFLAGS: ${CMAKE_CXX_FLAGS}") 

outputs a conclusion

 CXXFLAGS: -foo 

Questions

We found that CMake will create object files using -foo in both cases. So, -foo definitely CXXFLAGS into CXXFLAGS .

What is the difference between the first set of CMake code and the second set of CMake code?

Why is CMAKE_CXX_FLAGS canceled in one instance and installed in another instance?

+18
cmake compiler-options
source share
1 answer
  • CMAKE_CXX_FLAGS used to add flags for all C ++ purposes. It is convenient to pass general arguments such as warning levels or selected C ++ standards. It does not affect C or Fortran targets, and the user can pass additional flags.

  • add_compile_options adds parameters to all targets in the directory and its subdirectories. This is convenient if you have a library in the directory and you want to add parameters to all objects associated with the library, but not related to all other objects. In addition, add_compile_options can handle arguments with a generator expression. The documentation clearly states that

This command can be used to add any parameters, but alternative commands exist to add preprocessor definitions ( target_compile_definitions() and add_definitions() ) or include directories ( target_include_directories() and include_directories() ).

  • add_definitions intended for passing values โ€‹โ€‹of a preprocessor of the type -DFOO -DBAR=32 ( /D on Windows), which defines and sets preprocessor variables. You can pass any flag, but the flags of the above form will be detected and added to the [COMPILE_DEFINITIONS][2] property, which you can later read and change. You can also use generator expressions here. The documentation indicates the scope for directories, targets, and source files.

For this purpose, CMake will collect all flags from CMAKE_CXX_FLAGS , the target and the COMPILE_DEFINITIONS directory COMPILE_DEFINITIONS and all add_compile_options that affect the target.
CMAKE_CXX_FLAGS not modified by other commands or vice versa. This will violate the scope of these commands.

+22
source share

All Articles