使用Cmake,我想将一些通用标志应用于可执行文件和库。
嗯,我想我可以通过使用PUBLIC关键字来使用target_compile_options。我在一个小示例上测试了一个可执行文件和一个静态库,它们都只有一个文件(main.c&mylib.c),但这并不像预期的那样工作。
根CMakeLists.txt如下所示:
cmake_minimum_required(VERSION 3.0)
# Add the library
add_subdirectory(mylib)
# Create the executable
add_executable(mytest main.c)
# Link the library
target_link_libraries(mytest mylib)
# Add public flags
target_compile_options(mytest PUBLIC -Wall)
以及图书馆的CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
add_library(mylib STATIC mylib.c)
标志-Wall仅应用于main.c,而不应用于库文件(mylib.c):
[ 25%] Building C object mylib/CMakeFiles/mylib.dir/mylib.c.o
cd /patsux/Programmation/Repositories/test-cmake-public/build/mylib && /usr/lib/hardening-wrapper/bin/cc -o CMakeFiles/mylib.dir/mylib.c.o -c /patsux/Programmation/Repositories/test-cmake-public/mylib/mylib.c
[ 50%] Linking C static library libmylib.a
[ 25%] Building C object CMakeFiles/mytest.dir/main.c.o
/usr/lib/hardening-wrapper/bin/cc -Wall -o CMakeFiles/mytest.dir/main.c.o -c /patsux/Programmation/Repositories/test-cmake-public/main.c
现在,如果将标志应用于库而不是可执行文件,那么就可以了。
# Add public flags on the library
target_compile_options(mylib PUBLIC -Wall)
我得到:
[ 25%] Building C object mylib/CMakeFiles/mylib.dir/mylib.c.o
cd /patsux/Programmation/Repositories/test-cmake-public/build/mylib && /usr/lib/hardening-wrapper/bin/cc -Wall -o CMakeFiles/mylib.dir/mylib.c.o -c /patsux/Programmation/Repositories/test-cmake-public/mylib/mylib.c
[ 50%] Linking C static library libmylib.a
[ 75%] Building C object CMakeFiles/mytest.dir/main.c.o
/usr/lib/hardening-wrapper/bin/cc -Wall -o CMakeFiles/mytest.dir/main.c.o -c /patsux/Programmation/Repositories/test-cmake-public/main.c
[100%] Linking C executable mytest
在库中设置诸如目标类型之类的通用标志是没有意义的。
如何正确共享通用标志?我知道我可以使用add_definitions()。这是正确的方式吗?
我还测试了:
set_target_properties(mytest PROPERTIES COMPILE_FLAGS -Wall)
但是旗帜是不公开的。
您可以在根文件中添加这样的标志:
add_compile_options(-Wall)
或者,如果您使用的是3.0之前的cmake版本:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")