简体   繁体   English

如何在 CMake 中添加“-l”(ell)编译器标志

[英]How to add "-l" (ell) compiler flag in CMake

Work on Ubuntu 16在 Ubuntu 16 上工作

I used g++ main.cpp -lpq command for compiler my small project.我使用g++ main.cpp -lpq命令编译我的小项目。 Now I use Clion and wanna do same what I do with g++ .现在我使用Clion并想做与g++相同的操作。 But I can't add compiler flags in cmake file and get compile error.但我无法在cmake文件中添加编译器标志并得到编译错误。

cmake_minimum_required(VERSION 3.5.1)
project(day_g)

set(CMAKE_CXX_FLAGS "-lpq")

add_definitions(-lpq)

message("CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)
add_executable(day_g ${SOURCE_FILES})

Also I run only cmake file and get CMAKE_CXX_FLAGS with -lpq flag.此外,我只运行 cmake 文件并获得带有-lpq标志的CMAKE_CXX_FLAGS

CMAKE_CXX_FLAGS is -lpq
-- Configuring done
-- Generating done

How properly add compiler flags to cmake file?如何正确地将编译器标志添加到 cmake 文件?

Flag -l is for linker , not for compiler .标志-l用于链接器,而不是用于编译器 This flag is used for link with libraries.此标志用于与库的链接。 CMake has special command target_link_libraries for that purpose:为此,CMake 有特殊的命令target_link_libraries

target_link_libraries(day_g pq)

-lq is not a compiler flag (CFLAGS) but a linker flag. -lq 不是编译器标志 (CFLAGS),而是链接器标志。

To pass a library in a CMake project you should use:要在 CMake 项目中传递库,您应该使用:

target_link_libraries(target_name libraries...)

Note that if you specify 'q' as library the project will link with libq.a or, if you are on windows q.dll.请注意,如果您将“q”指定为库,则项目将与 libq.a 链接,或者,如果您在 windows q.dll 上。

... in your CMakeLists.txt the correct line to add is: ...在您的 CMakeLists.txt 中,要添加的正确行是:

target_link_libraries(day_g pq)

Note also that when you add a CFLAG you should also "remember" the previous ones that may be added by libraries or by your platform, ie:另请注意,当您添加 CFLAG 时,您还应该“记住”以前可能由库或您的平台添加的那些,即:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")

To check the exact flags cmake is passing to compiler or linker you can always run, from the build directory, the following command:要检查 cmake 传递给编译器或链接器的确切标志,您始终可以从构建目录运行以下命令:

make VERBOSE=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM