【问题标题】:Link error with static library in C++20 module与 C++20 模块中的静态库链接错误
【发布时间】:2021-04-26 10:57:32
【问题描述】:

我正在学习 C++20 模块功能,但每当我尝试在模块中包含头文件然后尝试链接它时,都会出现链接错误。我在使用 GLFW 库时遇到了错误,但我做了一个可重现的最小示例,以便您可以更轻松地帮助我。

以下是重现此问题的步骤:

  1. 获取带有函数定义的.a 文件:
// lib.h
void libraryFunction();
// lib.cpp
#include "lib.h"

void libraryFunction() {}
clang++ -c -o lib.o lib.cpp
ar rc lib.a lib.o
  1. 现在您有了lib.a 文件,编写并编译一个使用它的模块:
// test.cpp
export module test;
#include "lib.h"

export void testFunction() {
    libraryFunction();
}
clang++ -std=c++20 -c -fmodules-ts -Xclang -emit-module-interface -o test.pcm test.cpp
  1. 写一个main.cpp文件并尝试编译和链接它:
clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. -o main main.cpp test.cpp -l:lib.a -L.
  1. 你应该得到这个错误:
/usr/bin/ld: /tmp/test-25d7c8.o: in function `testFunction()':
test.cpp:(.text+0x5): undefined reference to `_ZW4testE15libraryFunctionv'
clang-11: error: linker command failed with exit code 1 (use -v to see invocation)

我该如何解决这个问题?当我 #include "lib.h" 并在 main.cpp 中调用 libraryFunction() 时,我没有收到错误,但我想要的是从模块调用库 API。这可能吗?

【问题讨论】:

标签: c++ static-libraries linker-errors c++20 static-linking


【解决方案1】:

您已将#include 放在模块下方,这可能将libraryFunction 声明为模块函数。这是有道理的,因为链接器会寻找类似 @​​987654326@ 的东西。

MS sources on modules(使用 MS 作为可靠来源的好时机)说您可以包含“全局”标头,但应该在第一个 module 声明之前完成。

尝试切换顺序:

// test.cpp
#include "lib.h"

export module test;

export void testFunction() {
    libraryFunction();
}

应该有帮助。

【讨论】:

  • 您首先需要 module; 来允许这样的 #includes,尽管 MSVC 可能还没有强制执行,因为它们的实施早于该规则。
  • @DavisHerring 我用 std2a 在 clang10 上测试了这个。如果您能指出我很乐意纠正的来源。我不会假装我是模块方面的专家,而且资源还很稀缺。我读了clang doc's on modules 并没有看到要求,但也许他们也(太)友好了。
  • 我只有the standard:Modules 文档确实存在的大部分内容都是基于(不同的)预标准化实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
  • 2015-09-07
  • 2013-09-03
  • 1970-01-01
  • 2021-10-22
相关资源
最近更新 更多