Question

I have a project with the following structure

  /cmake_modules/
    FindSFML.cmake
  /includes/
    car.hpp
    motor.hpp
    tires.hpp
  /sources/
    car.cpp
    motor.cpp
    tires.cpp    
  /main.cpp
  /main.hpp

I have the following CMakeFiles.txt file:

cmake_minimum_required(VERSION 2.8)

project (MYGAME)
set (MYGAME_VERSION_MAJOR 1)
set (MYGAME_VERSION_MINOR 0)

set (EXECUTABLE_NAME "mygame")

include_directories ("${MYGAME_BINARY_DIR}")
include_directories ("${MYGAME_BINARY_DIR}/includes")
link_directories ("${MYGAME_BINARY_DIR}/sources")

add_executable(${EXECUTABLE_NAME} main.cpp)

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
find_package(SFML 2.0 REQUIRED system window graphics network audio)

target_link_libraries(${EXECUTABLE_NAME} ${SFML_LIBRARIES})

When I try to execute make I get this:

[100%] Building CXX object CMakeFiles/mygame.dir/main.cpp.o
Linking CXX executable mygame
CMakeFiles/mygame.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x11): undefined reference to `mynamespace::Car::Instance()'
main.cpp:(.text+0x21): undefined reference to `mynamespace::Car::start()'
collect2: error: ld returned 1 exit status
make[2]: *** [mygame] Error 1
make[1]: *** [CMakeFiles/mygame.dir/all] Error 2
make: *** [all] Error 2

How do I fix it?

Was it helpful?

Solution

You need to include the rest of your sources (car.cpp, motor.cpp and tires.cpp) in the build in some way.

You can either add them along with main.cpp in the executable directly:

set(MySources sources/car.cpp sources/motor.cpp sources/tires.cpp main.cpp)
add_executable(${EXECUTABLE_NAME} ${MySources})

or you can make these into a library and link that:

set(MyLibSources sources/car.cpp sources/motor.cpp sources/tires.cpp)
add_library(MyLib ${MyLibSources})
add_executable(${EXECUTABLE_NAME} main.cpp)
...
target_link_libraries(${EXECUTABLE_NAME} MyLib ${SFML_LIBRARIES})

A couple of other points to note:

You should avoid the use of link_directories if possible (its own documentation discourages its use), and it's often helpful to include the headers in the list of files added via add_executable or add_library since these then show up in IDEs like MS Visual Studio.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top