Issue
I'm creating a project that makes use of CMake.
I have an include
folder for headers and an src
folder for source code. When attempting to build the project with cmake --build .
, I get an "undefined reference"
error:
/sdcard/dev/cpp/Bedrock++/src/main.cpp:(.text+0x70): undefined
reference to `ChatFormat::Blue'
Additional detail below:
$ cmake --build .
-- Configuring done
-- Generating done
-- Build files have been written to: /sdcard/dev/cpp/Bedrock++
Scanning dependencies of target Bedrock++
[ 33%] Building CXX object src/CMakeFiles/Bedrock++.dir/Server.cpp.o
[ 66%] Building CXX object src/CMakeFiles/Bedrock++.dir/main.cpp.o
[100%] Linking CXX executable Bedrock++
CMakeFiles/Bedrock++.dir/main.cpp.o: In function `main':
/sdcard/dev/cpp/Bedrock++/src/main.cpp:(.text+0x70): undefined
reference to `ChatFormat::Blue'
clang-5.0: error: linker command failed with exit code 1 (use -v to see
invocation)
make[2]: *** [src/CMakeFiles/Bedrock++.dir/build.make:121:
src/Bedrock++] Error 1
make[1]: *** [CMakeFiles/Makefile2:86:
src/CMakeFiles/Bedrock++.dir/all] Error 2
make: *** [Makefile:130: all] Error 2
Project root CMakeLists.txt
cmake_minimum_required(VERSION 2.8.7)
# Build all dependent libraries as static
project(Bedrock++)
#add_subdirectory(lib/json)
add_subdirectory(src)
add_subdirectory(include)
src/CMakeLists.txt
project(bedrock++)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
include_directories("${PROJECT_SOURCE_DIR}/include")
file(GLOB SOURCES "*.cpp")
add_executable(${PROJECT_NAME} ${SOURCES})
include/CMakeLists.txt
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" FILES_MATCHING PATTERN "*.h")
main.cpp
#include <iostream>
#include <string>
#include "util/ChatFormat.h"
int main()
{
std::cout << "Hello World! " << ChatFormat::Blue << "hey" << std::endl;
}
The ChatFormat.h
header is found in include/util/ChatFormat.h
and contains the following for every different colour:
static const std::string Black;
I've attempted to solve the problem myself to no avail with hours of research on the internet proving to be a dead end. I hope I didn't miss something obvious.
Any help would be greatly appreciated.
Solution
The CMake output suggests that 'ChatFormat.cpp', which contains the definition of 'ChatFormat::Black', is not being compiled. Only 'Server.cpp' and 'main.cpp' are being compiled.
I'm guessing that 'ChatFormat.cpp', like it's corresponding header, is under a 'utils' directory? But the GLOB command you are using to find your source files will only be finding files name *.cpp in the root folder. You might want to try changing 'GLOB' to 'GLOB_RECURSE' so it will pick up files in subfolders, though it is generally recommended that you avoid using globbing entirely and list each source file explicitly...
Answered By - Sean Burton Answer Checked By - Timothy Miller (WPSolving Admin)