I'm learning the C++20 modules feature, but whenever I try to include a header file inside a module and then try to link it, I get a link error. I got the error when working with the GLFW library, but I made a minimum reproducible example so you can help me more easily.
Here are the steps to reproduce this issue:
.a
file with a function definition:// lib.h
void libraryFunction();
// lib.cpp
#include "lib.h"
void libraryFunction() {}
clang++ -c -o lib.o lib.cpp
ar rc lib.a lib.o
lib.a
file, write and compile a module that uses it:// 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
main.cpp
file and try to compile and link it:clang++ -std=c++20 -fmodules-ts -fprebuilt-module-path=. -o main main.cpp test.cpp -l:lib.a -L.
/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)
How do I fix this? I don't get the error when I #include "lib.h"
and call libraryFunction()
in main.cpp
, but what I want is to call the library API from a module. Is this possible?
You've put #include
below module, which probably declared libraryFunction
as a module function. It makes sense, since linker looks for something like test-libraryFunction
.
MS sources on modules (what a time to be alive to use MS as credible source) say you can include "global" headers but it should be done before 1st module
declaration.
Try switching the order:
// test.cpp
#include "lib.h"
export module test;
export void testFunction() {
libraryFunction();
}
Should help.