如何在CMake中为同目录下的C++代码添加-std=c++11编译标志,而不作用于C代码
Great question! You’re right that add_compile_options() applies flags to all languages, which causes headaches with C code on macOS. Luckily, CMake has several ways to replicate the Autotools-style separation between C and C++ flags. Here are the most common and recommended approaches:
1. Use CMake's C++ Standard Variables (Preferred)
This is the modern, cross-platform-friendly way to set the C++ standard without manual compiler flags. Add these lines to your CMakeLists.txt:
# Set the C++ standard to 11 set(CMAKE_CXX_STANDARD 11) # Require the standard (fail if the compiler doesn't support it) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Disable compiler-specific extensions (uses pure C++11 instead of gnu++11) set(CMAKE_CXX_EXTENSIONS OFF)
This approach automatically handles compiler differences (like using /std:c++11 for MSVC instead of -std=c++11 for GCC/Clang) and only affects C++ targets—your C code will use the default C standard without extra flags.
2. Set CMAKE_CXX_FLAGS (Direct Autotools Equivalent)
If you want a direct parallel to Autotools’ CXXFLAGS and CFLAGS, modify the C++-specific flag variable directly:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
Just like Autotools uses CXXFLAGS for C++ and CFLAGS for C, CMAKE_CXX_FLAGS only applies to C++ compilation, while CMAKE_C_FLAGS controls C code. This is a solid choice if you need to add other C++-specific flags too.
3. Target-Specific Flags with Generator Expressions
If you only want to apply the C11 flag to specific targets (instead of all C code in your project), use generator expressions with target_compile_options:
# Apply to a specific target target_compile_options(your_target_name PRIVATE $<COMPILE_LANGUAGE:CXX>:-std=c++11)
The $<COMPILE_LANGUAGE:CXX> generator expression ensures the flag is only added when compiling C++ files for that target. This is useful if you have multiple targets with different standard requirements.
All these methods avoid applying -std=c++11 to your C code, so you won’t run into the macOS compilation errors you mentioned.
内容的提问来源于stack exchange,提问作者Edward Hartnett

