I created a project with some nested library dependencies using the OBJECT library type. The motivation for this is to avoid link order issues with static libraries.
I have a simple directory structure as follows:
├── bar
│ ├── bar.c
│ └── bar.h
├── foo
│ ├── foo.c
│ └── foo.h
├── main.c
└── CMakeLists.txt
foo depends on bar, and main depends on foo. For example,
bar.c
#include "bar.h"
#include <stdio.h>
void bar(void) {
printf("woot woot\n");
}
foo.c
#include "foo.h"
#include "bar.h"
void foo(void) {
bar();
}
main.c
#include "foo.h"
int main() {
foo();
return 0;
}
The CMakeLists.txt
cmake_minimum_required(VERSION 3.18)
project(myproj)
enable_language(C ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)
# build bar
add_library(bar OBJECT ${PROJECT_SOURCE_DIR}/bar/bar.c)
target_include_directories(bar PUBLIC ${PROJECT_SOURCE_DIR}/bar)
# build foo, depends on bar
add_library(foo OBJECT ${PROJECT_SOURCE_DIR}/foo/foo.c)
target_include_directories(foo PUBLIC ${PROJECT_SOURCE_DIR}/foo)
target_link_libraries(foo PUBLIC bar)
# build executable, depends on foo
add_executable(myexe ${PROJECT_SOURCE_DIR}/main.c)
target_link_libraries(myexe PUBLIC foo)
My expectation is that myexe would inherit the bar dependency from foo when it links to it. However, this is not the case it seems. When the code is compiled, main.o only links to foo.o, and thus there is an undefined reference to bar. However, if I change the library types from OBJECT to STATIC everything works fine. Why does this happen?