Recently I am learning cmake on Ubuntu, so I wrote a simply code to learn to build a static library.
The structure of the workspace in VScode is:
.
├── CMakeLists.txt
├── include
│ └── static
│ └── sum_of_two.hh
├── src
│ ├── main.cc
│ └── sum_of_two.cc
└── .vscode
└── c_cpp_properties.json
CMakeLists.txt:
cmake_minimum_required(VERSION 3.22)
project(learn_cmake)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR})
add_library(sum_of_two STATIC src/sum_of_two.cc)
target_include_directories(sum_of_two PUBLIC ${PROJECT_SOURCE_DIR}/include)
add_executable(main src/main.cc)
target_link_libraries(main PUBLIC sum_of_two)
main.cc:
#include <iostream>
#include "static/sum_of_two.hh"
int main() {
int a, b;
std::cin >> a >> b;
std::cout << sum_of_two(a, b) << std::endl;
return 0;
}
sum_of_two.hh:
#ifndef __SUM_OF_TWO_HH__
#define __SUM_OF_TWO_HH__
inline int sum_of_two(int a, int b);
#endif // __SUM_OF_TWO_HH__
sum_of_two.cc:
#include "static/sum_of_two.hh"
inline int sum_of_two(int a, int b) { return a + b; }
And when I try to make the final target, I get the following error:
/usr/bin/ld: CMakeFiles/main.dir/src/main.cc.o: in function `main':
main.cc:(.text+0x4e): undefined reference to `sum_of_two(int, int)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/main.dir/build.make:98: ../main] Error 1
make[1]: *** [CMakeFiles/Makefile2:111: CMakeFiles/main.dir/all] Error 2
make: *** [Makefile:91: all] Error 2
I have tried many methods on modifying the CMakeLists.txt, but none worked out. However, if I move the function inside a class, it worked out. For example, after I modify sum_of_two.hh to:
#ifndef __SUM_OF_TWO_HH__
#define __SUM_OF_TWO_HH__
class Hello
{
private:
int a, b;
public:
Hello();
Hello(int a, int b);
void print();
int sum_of_two();
};
#endif
It will not raise errors related to sum_of_two()
. I am wondering why this happens.