Search code examples
openglcmakeundefined-symbol

Undefined symbol for custom .h and cpp using CMake


It's been over a decade since I used C++ and this whole CMake thing is completely new to me. My question is specifically how do I configure a CMake project so that it won't get this undefined symbol error.

The error message is below:

====================[ Build | glfw_template | Debug ]===========================
"/Users/brianyeh/Library/Application Support/JetBrains/Toolbox/apps/CLion/ch-0/193.6911.21/CLion.app/Contents/bin/cmake/mac/bin/cmake" --build /Users/brianyeh/CLionProjects/glfw_template/cmake-build-debug --target glfw_template -- -j 4
[ 50%] Linking CXX executable bin/glfw_template
Undefined symbols for architecture x86_64:
  "_LoadShaders", referenced from:
      init() in main.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [bin/glfw_template] Error 1
make[2]: *** [CMakeFiles/glfw_template.dir/all] Error 2
make[1]: *** [CMakeFiles/glfw_template.dir/rule] Error 2
make: *** [glfw_template] Error 2

Please reference this link to see the project: https://github.com/crimsonalucard/glfw_template

The desired behavior is that the project compiles under CMake.


Solution

  • You need to build your executable with all of the .cpp files used in your project.

    Examples from these links:

    http://derekmolloy.ie/hello-world-introductions-to-cmake/

    Adding header and .cpp files in a project built with cmake

    Suggest doing something like this in your cmakelists:

    file(GLOB SOURCES
        lib/*.cpp
        include/*.h
        main.cpp
    )
    
    add_executable(glfw_template ${SOURCES})
    

    EDIT: As per comments GLOB is not recommended, the preferred method is to manually add all sources to a cultivated list:

    set(SOURCES lib/LoadShaders.cpp lib/vgl.cpp)
    set(HEADERS include/LoadShaders.h include/vgl.h)
    
    add_executable(glfw_template ${SOURCES} ${HEADERS})