简体   繁体   中英

Change the order of compiler flags

To prevent "undefined reference to..." boost errors, I need to append the boost libraries at the very end of the compiler flags. Therefore, in CMakeLists.txt I set:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pedantic -O0 -Wall -DBOOST_SYSTEM_NO_DEPRECATED -lboost_system -lboost_filesystem")

However, verbose output of cmake shows me that additional flags are appended behind the ones I defined:

g++ -std=c++11 -pedantic -O0 -Wall -DBOOST_SYSTEM_NO_DEPRECATED -lboost_system -lboost_filesystem  CMakeFiles/My_Project.dir/main.cpp.o  -o My_Project  -L/usr/local/boost_1_60_0/lib

Is it possible to change the order?

The complete CMakeLists.txt:

cmake_minimum_required(VERSION 3.4)
project(My_Project)

set(CMAKE_VERBOSE_MAKEFILE ON)

# This is bad but I currently don't have another working solution.
set(BOOSTROOT "/usr/local/boost_1_60_0/")
set(BOOST_ROOT "/usr/local/boost_1_60_0/")

find_package(Boost 1.60.0 COMPONENTS system filesystem REQUIRED)
if(Boost_FOUND)

    message(STATUS "Boost_INCLUDE_DIRS: ${Boost_INCLUDE_DIRS}")
    message(STATUS "Boost_LIBRARIES: ${Boost_LIBRARIES}")
    message(STATUS "Boost_VERSION: ${Boost_VERSION}")

    link_directories(${Boost_LIBRARY_DIRS})
    include_directories(${Boost_INCLUDE_DIRS})

endif()

add_executable(BoostTest main.cpp)

if(Boost_FOUND)

    target_link_libraries(BoostTest ${Boost_LIBRARIES})

endif()

# Boost libraries appended at the end. However, cmake generates flags like this:
# c++ -std=c++11 -pedantic -O0 -Wall -DBOOST_SYSTEM_NO_DEPRECATED -lboost_system -lboost_filesystem  CMakeFiles/My_Project.dir/main.cpp.o  -o My_Project  -L/usr/local/boost_1_60_0/lib
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pedantic -O0 -Wall -DBOOST_SYSTEM_NO_DEPRECATED -lboost_system -lboost_filesystem")
set(SOURCE_FILES main.cpp)
add_executable(My_Project ${SOURCE_FILES})

Thanks

You should use target_link_libraries instead of manually appending -lboost directives into your compiler flags.

TARGET_LINK_LIBRARIES(My_Project boost)

It should also be mentioned that it's possible the linker might be invoked as a separate invocation after the compilation of object files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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