Boost.Test 与预编译 headers (PCH) 一起使用时出现链接器错误

Boost.Test linker error by use with precompiled headers (PCH)

我在将 Boost.Test 与预编译 header (PCH) 一起使用时出现链接器错误,如果没有 PCH,该错误就不会发生。我使用 Usage variants 中描述的动态链接库。 如何修复错误以将 Boost.Test 也与 PCH 一起使用?

问题至少出现在 Fedora 和 boost 1.73(只有动态库)和 g++ 10/clang 11 上。

    $ cmake ../ && make
    -- Configuring done
    -- Generating done
    -- Build files have been written to: /home/.../boost_test_pch/build
    [ 33%] Building CXX object CMakeFiles/boost_utf_pch.dir/test_driver.cpp.o
    [ 66%] Building CXX object CMakeFiles/boost_utf_pch.dir/test.cpp.o
    [100%] Linking CXX executable boost_utf_pch
    [100%] Built target boost_utf_pch

对比

    $ cmake -DEDA_ENABLE_PCH=TRUE ../ && make
    -- Configuring done
    -- Generating done
    -- Build files have been written to: /home/.../boost_test_pch/build
    [ 25%] Building CXX object CMakeFiles/boost_utf_pch.dir/cmake_pch.hxx.gch
    [ 50%] Building CXX object CMakeFiles/boost_utf_pch.dir/test_driver.cpp.o
    cc1plus: warning: /home/.../boost_test_pch/build/CMakeFiles/boost_utf_pch.dir/cmake_pch.hxx.gch: not used because `BOOST_TEST_DYN_LINK' is defined [-Winvalid-pch]
    [ 75%] Building CXX object CMakeFiles/boost_utf_pch.dir/test.cpp.o
    [100%] Linking CXX executable boost_utf_pch
    /usr/bin/ld: /usr/lib/gcc/x86_64-redhat-linux/10/../../../../lib64/crt1.o: in function `_start':
    (.text+0x24): undefined reference to `main'
    collect2: error: ld returned 1 exit status
    make[2]: *** [CMakeFiles/boost_utf_pch.dir/build.make:138: boost_utf_pch] Error 1
    make[1]: *** [CMakeFiles/Makefile2:95: CMakeFiles/boost_utf_pch.dir/all] Error 2
    make: *** [Makefile:103: all] Error 2

我无法对之前的警告消息执行任何操作...

这里是 playground 文件:

Alan Birtles 得到了正确方向的提示。我不知道编译器开关 BOOST_TEST_DYN_LINK 对 PCH 上下文中单个文件的影响。项目所有文件的定义,格式为:

    target_compile_definitions(${PROJECT_NAME} PRIVATE
        "BOOST_TEST_DYN_LINK")  

一头雾水不能解决问题。只有在为驱动程序 'main' 设置 属性 SKIP_PRECOMPILE_HEADERS 后,它才会按预期编译和链接:

    project(boost_utf_pch LANGUAGES CXX)
    cmake_minimum_required(VERSION 3.18)

    add_executable(${PROJECT_NAME} "")

    find_package(Boost 1.73.0 REQUIRED COMPONENTS 
        unit_test_framework)

    target_sources(${PROJECT_NAME} PRIVATE
        test_driver.cpp test.cpp)

    target_link_libraries(${PROJECT_NAME} PRIVATE
        Boost::unit_test_framework)

    set_source_files_properties(test_driver.cpp
        APPEND PROPERTIES COMPILE_DEFINITIONS "BOOST_TEST_DYN_LINK")
    set_source_files_properties(test_driver.cpp
        PROPERTIES SKIP_PRECOMPILE_HEADERS ON)
        
    option(EDA_ENABLE_PCH "Enable PCH" ON)

    if (EDA_ENABLE_PCH)
        target_precompile_headers(${PROJECT_NAME} PRIVATE pch.hpp)
    endif()