0

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.

273K
  • 29,503
  • 10
  • 41
  • 64
user2448361
  • 155
  • 2
  • 10
  • I'm pretty sure the problem is that you're not exporting your `MyTest` class / its interface functions. See also https://cmake.org/cmake/help/latest/module/GenerateExportHeader.html. Good job with posting an [mre] though. – starball Feb 22 '23 at 05:32
  • 1
    Since you use `-fvisibility=hidden`, then you should now that it prevents exporting symbols by default. CMake has platform-independent representation of this flag: [_VISIBILITY_PRESET](https://cmake.org/cmake/help/latest/prop_tgt/LANG_VISIBILITY_PRESET.html), so it is better to use that property. – Tsyvarev Feb 22 '23 at 07:44

0 Answers0