CMake 生成的程序无法在 Windows 上链接:尝试链接到不存在的文件

CMake generated program fails to link on Windows: tries to link to non-existent file

本文关键字:链接 文件 不存在 Windows 程序 CMake      更新时间:2023-10-16

我正在尝试在Windows上编译一个非常简单的测试程序,但不断收到链接器错误。要链接的程序如下:

#include <boost/asio/io_context.hpp>
int main()
{
boost::asio::io_context context;
}

虽然CMakeLists.txt看起来像这样:

cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(windows-test)
SET(CMAKE_CXX_STANDARD 17)
find_package(Boost 1.6.7 COMPONENTS system)
include_directories("${Boost_INCLUDE_DIRS}")
add_executable(windows-test main.cpp)
target_link_libraries(windows-test Boost::system)

使用 nmake 构建此内容时,它会失败并显示以下输出:

-- Boost version: 1.67.0
-- Found the following Boost libraries:
--   system
-- Configuring done
-- Generating done
-- Build files have been written to: Z:/windows-test/build
[ 50%] Linking CXX executable windows-test.exe
LINK Pass 1: command "C:PROGRA~2MICROS~12017BUILDT~1VCToolsMSVC1414~1.264binHostx64x64link.exe /nologo @CMakeFileswindows-test.dirobjects1.rsp /out:windows-test.exe /implib:windows-test.lib /pdb:Z:windows-testbuildwindows-test.pdb /version:0.0 /machine:x64 /debug /INCREMENTAL /subsystem:console C:localboost_1_67_0lib64-msvc-14.1boost_system-vc141-mt-gd-x64-1_67.lib kernel32.lib user32.lib gdi32.lib winspool.lib shell32.lib ole32.lib oleaut32.lib uuid.lib comdlg32.lib advapi32.lib /MANIFEST /MANIFESTFILE:CMakeFileswindows-test.dir/intermediate.manifest CMakeFileswindows-test.dir/manifest.res" failed (exit code 1104) with the following output:
LINK : fatal error LNK1104: cannot open file 'libboost_system-vc141-mt-gd-x64-1_67.lib'
NMAKE : fatal error U1077: '"C:Program FilesCMakebincmake.exe"' : return code '0xffffffff'
Stop.
NMAKE : fatal error U1077: '"C:Program Files (x86)Microsoft Visual Studio2017BuildToolsVCToolsMSVC14.14.26428binHostX64x64nmake.exe"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:Program Files (x86)Microsoft Visual Studio2017BuildToolsVCToolsMSVC14.14.26428binHostX64x64nmake.exe"' : return code '0x2'
Stop.

文件'libboost_system-vc141-mt-gd-x64-1_67.lib'确实存在于系统上,但我不知道它来自哪里,因为它没有出现在它正在执行的链接器命令上。链接器命令显示文件 C:\local\boost_1_67_0\lib64-msvc-14.1\boost_system-vc141-mt-gd-x64-1_67.lib,该文件确实存在。

为什么哦,为什么它会尝试链接到链接器命令中没有出现的丢失文件?我觉得这里超出了我的深度,因为我已经将近 20 年没有使用 Windows,以前也从来没有移植到它。

Boost 标头包含Windows 上的链接器命令,因此在包含适当的标头时会自动链接 Boost 库。但是,您的设置似乎对库使用了不同的命名方案,这使得这些库无法链接。

您可以通过定义预处理器宏BOOST_ALL_NO_LIB来禁用 Boost 自动链接功能。喜欢这个:

target_compile_definitions(windows-test PRIVATE BOOST_ALL_NO_LIB)