Situation:
Let's say I have 2 libraries (libA.a, libB.a) I want to use in an executable (exec.cpp).
My libA includes foo(x) which is used in libB's function bar(y). Thus, I include the header of libA in libB, and then include the header of libB in my executable and link both:
A.h:
#ifndef LIB_A_INCLUDED
#define LIB_A_INCLUDED
int foo(int x);
#endif
A.cpp:
int foo(int x) {
//DO stuff
}
B.h
#ifndef LIB_B_INCLUDED
#define LIB_B_INCLUDED
#include <A.h>
int bar(int y);
#endif
B.cpp:
int bar(int y) {
foo(y);
//more stuff
}
The CMakeLists file for the two libaries looks like this (for libB there's also an include_directories call to include A.h):
cmake_minimum_required(VERSION 3.15)
project(libA)
set(CMAKE_CXX_STANDARD 14)
add_library(libA A.h A.c)
Exec.cpp:
#include<B.h>
int main() {
bar(42);
return 0;
}
The CMakeLists file for the executable looks like this:
cmake_minimum_required(VERSION 3.15)
project(Exec)
set(CMAKE_CXX_STANDARD 14)
include_directories("PATH_TO_HEADER_A/A.h" "PATH_TO_HEADER_B/B.h")
add_executable(Exec main.cpp)
target_link_libraries(Exec "PATH_TO_LIB_A/libA.a;PATH_TO_LIB_B/libB.a")
Problem
This does not work! It yields:
/usr/bin/ld: PATH_TO_LIB_B/libB.a(B.c.o): in function `bar':
/usr/bin/ld: PATH_TO_LIB_B/B.cpp:95: undefined reference to `foo'
However, when I change Exec.cpp to:
#include<B.h>
int main() {
bar(42);
foo(31415);
return 0;
}
It compiles and works as expected - it seems the linker does not link libA when no functions of libA are used in exec.cpp directly, even though these functions are used in libB which is definitely using foo.
Question
Is there a way to force the link? How do I get this to work?