CMake:连续两次编译程序

CpC*_*d0y 5 compilation g++ cmake

为了能够进行许多自动优化,我希望能够-fprofile-generate首先使用标志编译我的程序,然后运行它以生成配置文件,然后重新编译程序-fprofile-use

这意味着我想连续编译我的程序两次,CMAKE_CXX_FLAGS每次编译两次。

我怎样才能使用 CMake 做到这一点?

小智 5

您可以构建一些内容,然后运行它,然后通过使用客户目标和“add_dependency”命令在执行后构建其他内容。对于您的 gcov 案例,您可能会执行以下操作:

配置文件.cxx

#include <iostream>
int main(void) {
    std::cout << "Hello from Generating Profile run" << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

CMakeLists.txt

cmake_minimum_required(VERSION 3.1 FATAL_ERROR)

project(profileExample C CXX)

# compile initial program
add_executable(profileGenerate profile.cxx)
set_target_properties(profileGenerate PROPERTIES COMPILE_FLAGS "-fprofile-
generate")
target_link_libraries(profileGenerate gcov)

add_executable(profileUse profile.cxx)
set_target_properties(profileUse PROPERTIES COMPILE_FLAGS "-fprofile-use")
target_link_libraries(profileUse gcov)

# custom target to run program
add_custom_target(profileGenerate_run
    COMMAND profileGenerate
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    COMMENT "run Profile Generate"
    SOURCES profile.cxx
    )

#create depency for profileUse on profileGenerate_run
add_dependencies(profileUse profileGenerate_run)
Run Code Online (Sandbox Code Playgroud)

输出显示构建 -> 运行 -> 构建

构建输出