用-fpic替换-fPIC

时间:2016-06-27 12:20:07

标签: c++ qt cmake

使用Qt时,CMake会自动将-fPIC标志添加到编译选项中。我想使用-fpic,因此我浏览了所有Cmake变量,并将-fPIC替换为-fpic

cmake_minimum_required(VERSION 3.5)
project(sss)

find_package(Qt5 REQUIRED COMPONENTS Core Sql)

get_cmake_property(_variableNames VARIABLES)
foreach (_variableName ${_variableNames})
        if (NOT "${${_variableName}}" STREQUAL "")
                string(REPLACE "-fPIC" "-fpic" ${_variableName} ${${_variableName}})
                string(REPLACE "-fPIE" "-fpie" ${_variableName} ${${_variableName}})
        endif()
        #message(STATUS "${_variableName}=${${_variableName}}")
endforeach()

set(CMAKE_CXX_FLAGS "-fpie")
set(CMAKE_EXE_LINKER_FLAGS "-fpie -pie")

add_executable(sss main.cpp)

target_link_libraries(sss Qt5::Core Qt5::Sql)

main.cpp包含

#include <QSqlDatabase>

int main(){
        QSqlDatabase::addDatabase("QPSQL");
}

不幸的是,CMake仍然添加了-fPIC标志,althoguh列出的变量不包含它:

Building CXX object CMakeFiles/sss.dir/main.cpp.o
/usr/bin/c++   -DQT_CORE_LIB -DQT_NO_DEBUG -DQT_SQL_LIB -isystem /usr/include/x86_64-linux-gnu/qt5 -isystem /usr/include/x86_64-linux-gnu/qt5/QtCore -isystem /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++-64 -isystem /usr/include/x86_64-linux-gnu/qt5/QtSql  -fPIC -o CMakeFiles/sss.dir/main.cpp.o -c src/main.cpp

如何将-fPIC替换为-fpic

1 个答案:

答案 0 :(得分:1)

将我的评论转化为答案

您的代码会覆盖CMake全局变量,例如CMAKE_CXX_COMPILE_OPTIONS_PICCMAKE_CXX_COMPILE_OPTIONS_PIE

但是Qt通过目标属性带来了自己的-fPIC选项。 Qt5::Core目标的INTERFACE_COMPILE_OPTIONS设置为-fPIC(请参阅here)。

尝试添加

覆盖目标属性
set_property(TARGET Qt5::Core PROPERTY INTERFACE_COMPILE_OPTIONS "-fpic")
find_package(Qt5 ...)来电后