Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impact of setting CMAKE_CXX_FLAG in a C++ project

Tags:

c++

cmake

I have a C++ project and I want to use CMake in the project. My project has multiple directories and sub-directories.

I have a top-level CMakeLists.txt which builds the whole project. I also have CMakeLists.txt in the sub-directories. I wanted to set the compiler flags but here is what I am confused about. Are the effects of the compiler flags in CMake apply only to the corresponding directory or will it apply to the whole project?

For example, my project (let's call it MyProject) has a CMakeLists.txt associated. The project has two subdirectories A and B. Each with its own CMakeLists.txt. In the A/CMakelist.txt, I have set the compiler flag as below:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y -Wno-narrowing")

The B/CMakeLists.txt is as below:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y")

What I do not understand is that whether the compiler will use the flag -Wno-narrowing for the cpp files in subdirectory B also (in general will it apply to the whole project)?

Is the scope of setting a compiler flag (in general any variable) in CMakeList.txt are applicable only to the corresponding directory or it will be applied globally throughout the project?

like image 532
Ankur Bose Avatar asked Feb 03 '26 17:02

Ankur Bose


1 Answers

CMake's set command works on function and directory scope. That is, if you set a variable like you did, outside of a CMake function, the effect will be visible in that directory and all of its subdirectories.

Whenever you define a new target (through calling add_executable or add_library), the value of the CMAKE_CXX_FLAG variable at that point will be used to determine the initial value of the target properties for the compile flags.

So the -Wno-narrowing option should not be able to leak over from one subdirectory to a sibling subdirectory.

A quick note on modern CMake style: Prefer using the compile features functionalities over setting the -std option directly. The former will be portable and work on all toolchains and compiler versions. For instance, to require C++14 globally for all targets in the project, simply set(CMAKE_CXX_STANDARD 14) in the top-level CMakelists. Similarly, consider using the target_compile_options command for setting options that only apply to certain targets of your project. Using that command is usually less error-prone than fiddling with the global variable everywhere. For manual toolchain-specific flags like -Wno-narrowing, consider wrapping them in a generator expression to make sure they will only be used on toolchains that supports the flag.

like image 121
ComicSansMS Avatar answered Feb 06 '26 06:02

ComicSansMS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!