我正在尝试打印为目标设置的编译标志。最好的情况是在配置和编译时打印一条带有当前标志的行,但是,如果不可能,则仅在配置时(或仅在编译时)(可接受的解决方案)。
这是我正在测试的.c文件:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
和CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(cmake_gcc_options_try_c C)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
add_executable(cmake_gcc_options_try_c main.c)
target_compile_options(cmake_gcc_options_try_c
PUBLIC -W -Wall -Wextra -pedantic -pedantic-errors)
# This fails
message("-- Current compiler flags CMAKE_C_FLAGS are: ${CMAKE_C_FLAGS}")
message("-- Current compiler flags C_FLAGS are: ${C_FLAGS}")
和
cmake . && make
给出以下输出:
-- The C compiler identification is GNU 7.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Current compiler flags CMAKE_C_FLAGS are:
-- Current compiler flags C_FLAGS are:
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/Projects/cmake-gcc-options-try-c
Scanning dependencies of target cmake_gcc_options_try_c
[ 50%] Building C object CMakeFiles/cmake_gcc_options_try_c.dir/main.c.o
[100%] Linking C executable cmake_gcc_options_try_c
[100%] Built target cmake_gcc_options_try_c
为什么打印CMAKE_C_FLAGS
和C_FLAGS
时未定义?
如何通过make
命令实现此打印:
[ 50%] Building C object CMakeFiles/cmake_gcc_options_try_c.dir/main.c.o
[ 50%] Current compiler flags are: -W -Wall -Wextra -pedantic -pedantic-errors -std=gnu11
[100%] Linking C executable cmake_gcc_options_try_c
[100%] Built target cmake_gcc_options_try_c
?
更新:Viktor Sergienko带有一个可行的解决方案,但与此相关的一个问题是它的打印效果不是很好: 有什么想法要使其成为其他印刷品的格式吗?例如:
[ 50%] Building C object CMakeFiles/cmake_gcc_options_try_c.dir/main.c.o
[100%] Linking C executable cmake_gcc_options_try_c
[100%] Current compiler flags are: -W -Wall -Wextra -pedantic -pedantic-errors -std=gnu11
[100%] Built target cmake_gcc_options_try_c
第二个问题是-std=gnu11
未打印(但已通过set(CMAKE_C_STANDARD 11)
和set(CMAKE_C_STANDARD_REQUIRED ON)
启用)
答案 0 :(得分:4)
使用:
这给了我;-list
在配置和编译时的选项:
cmake_minimum_required(VERSION 3.10)
project(cmake_gcc_options_try_c C)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
add_executable(cmake_gcc_options_try_c main.c)
target_compile_options(cmake_gcc_options_try_c
PUBLIC -W -Wall -Wextra -pedantic -pedantic-errors)
get_target_property(MAIN_CFLAGS cmake_gcc_options_try_c COMPILE_OPTIONS)
# also see: COMPILE_DEFINITIONS INCLUDE_DIRECTORIES
message("-- Target compiler flags are: ${MAIN_CFLAGS}")
add_custom_command(TARGET cmake_gcc_options_try_c POST_BUILD
COMMAND echo built with the flags: ${MAIN_CFLAGS})
更新问题后进行更新:要获取C / CXX标准,请查找C_STANDARD。 CMake只设置标志的-gnu
变体。
Update2:要获取每个源文件作为JSON文件的完整编译器/链接器命令,请将CMAKE_EXPORT_COMPILE_COMMANDS设置为ON
(仅在CMake 3.5 +,make
和{{ 1}}生成器)。值得赞扬的是弗洛里安在this question中的评论。