I am trying to write and use a class with inline member functions. However, upon building the project, the linker complains that it cannot find the symbols for these functions. I have created a minimal example that reproduces this error. There are two source files and one header file with the following contents.
class.h:
class Class {
public:
void someOperation();
};
class.cpp:
#include <iostream>
#include "class.h"
inline void Class::someOperation() {
std::cout << "Hello from the class!" << std::endl;
}
main.cpp:
#include "class.h"
int main() {
Class aClass;
aClass.someOperation();
return 0;
}
I am using CMake to build. My CMakeLists.txt looks like this:
cmake_minimum_required(VERSION 3.12)
project(test)
set(CMAKE_CXX_STANDARD 14)
add_executable(test main.cpp class.cpp)
All of these files reside in a single directory.
When I try to build the project I get the following output:
/bin/cmake --build /Users/daniel/test/bin --target test -- -j 4
Scanning dependencies of target test
[ 66%] Building CXX object CMakeFiles/test.dir/class.cpp.o
[ 66%] Building CXX object CMakeFiles/test.dir/main.cpp.o
[100%] Linking CXX executable test
Undefined symbols for architecture x86_64:
"Class::someOperation()", referenced from:
_main 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]: *** [test] Error 1
make[2]: *** [CMakeFiles/test.dir/all] Error 2
make[1]: *** [CMakeFiles/test.dir/rule] Error 2
make: *** [test] Error 2
However, when if I remove inline
from class.cpp the project builds successfully. Can anyone tell me why this goes wrong and what I can do to make this work?