I'm trying to compile a simple C++ app with CMake but I got
Consolidate compiler generated dependencies of target mylib
[ 25%] Linking CXX shared library libmylib.so
[ 50%] Built target mylib
Consolidate compiler generated dependencies of target app
[ 75%] Linking CXX executable app
/usr/bin/ld: CMakeFiles/app.dir/app.cc.o: in function `main':
app.cc:(.text.startup+0x38): undefined reference to `MyTest::MyTest()'
/usr/bin/ld: app.cc:(.text.startup+0x40): undefined reference to `MyTest::add()'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/app.dir/build.make:98: app] Error 1
make[1]: *** [CMakeFiles/Makefile2:111: CMakeFiles/app.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
Source code below
lib.h
class MyTest {
public:
MyTest();
void add();
};
lib.cc
#include "lib.h"
MyTest::MyTest() {
}
void MyTest::add() {
}
app.cc
#include "lib.h"
int main() {
MyTest test;
test.add();
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.17 FATAL_ERROR)
message("CMAKE_VERSION: ${CMAKE_VERSION}")
project(debug C CXX)
set(RELEASE_FLAGS "-O3 -fvisibility=hidden -fPIC")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${RELEASE_FLAGS}")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${RELEASE_FLAGS} -fvisibility-inlines-hidden -fno-omit-frame-pointer")
include_directories(.)
add_library(mylib SHARED "${CMAKE_CURRENT_LIST_DIR}/lib.cc")
target_link_libraries(mylib PRIVATE protobuf::libprotobuf)
add_executable(app "${CMAKE_CURRENT_LIST_DIR}/app.cc")
target_link_libraries(app PRIVATE mylib)
I have linked mylib
target to app
target already but for some reason, I still got undefined reference
error.