The problem is as followed: you have two files, one is for a library one is for the executable and you want to call a method defined in the library but declared in the executable:
lib.cpp:
extern void Method();
void DoStuff() {
Method();
}
main.cpp:
#include <iostream>
void Method() {
std::cout << "Do Stuff" << std::endl;
}
int main() {
Method();
return 0;
}
And now using cmake I just basically want to tell the library that the declaration of the DoStuff
method is in the executable target.
Using this simple CMakeLists.txt leads to an undefined symbol linker error:
Undefined symbols for architecture x86_64:
"Method()", referenced from:
DoStuff() in lib.cpp.o
CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(extern)
set(CMAKE_CXX_STANDARD 14)
add_library(myLib SHARED lib.cpp)
add_executable(exe main.cpp)
target_link_libraries(exe myLib)
The only way I found was to go through a temporary static library and link my shared library with that static library which I think is quite nasty because I soon I add more classes to the exectuable I get duplicate symbols (which totally makes sense since they are duplicate)
add_library(tmpLib STATIC main.cpp)
target_link_libraries(myLib tmpLib)
I've browsing the interwebs for two nights now looking for a way to do that and I'm still left with absolutely no clue.