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:
- Get a
.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
- Now that you have the
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
- Write a
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.
- You should get this error:
/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?