Project Sturcture
I am learning how to build a C++/cmake template. The structure looks like:
.
├── CMakeLists.txt
├── README.md
└── src
├── CMakeLists.txt
└── geometry
├── CMakeLists.txt
└── line
├── CMakeLists.txt
├── line.cpp
└── line.h
Every CMakeLists.txt
looks like the following:
./CMakeLists.txt
:
cmake_minimum_required(VERSION 3.20.0)
project(cmake_template VERSION 0.0.1 LANGUAGES CXX)
add_subdirectory(src)
./src/CMakeLists.txt
:
add_subdirectory(geometry)
./src/geometry/CMakeLists.txt
:
add_subdirectory(line)
./src/geometry/line/CMakeLists.txt
:
add_library(line line.cpp)
target_include_directories(line PUBLIC .)
And the implementation looks like:
line.h
:
#include <string>
class Line{
private:
std::string name;
public:
Line(std::string);
virtual void display();
};
line.cpp
:
#include "src/geometry/line/line.h"
#include <iostream>
Line::Line(std::string name):name(name){}
void Line::display(){
std::cout << "A line with name " << this->name << "\n";
}
Compile and error
The command I run is cmake -S . -B build && cmake --build build/
, and it shows the error:
[1/2] Building CXX object src/geometry/line/CMakeFiles/line.dir/line.cpp.o
FAILED: src/geometry/line/CMakeFiles/line.dir/line.cpp.o
/usr/bin/clang++ -I../src/geometry/line/. -g -MD -MT src/geometry/line/CMakeFiles/line.dir/line.cpp.o -MF src/geometry/line/CMakeFiles/line.dir/line.cpp.o.d -o src/geometry/line/CMakeFiles/line.dir/line.cpp.o -c ../src/geometry/line/line.cpp
../src/geometry/line/line.cpp:1:10: fatal error: 'src/geometry/line/line.h' file not found
#include "src/geometry/line/line.h"
^~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
ninja: build stopped: subcommand failed.
The code can compile if I change to #include "line.h"
My questions are:
- How can I include the absolute path without change the current structure? I.e., I don't want to change
CMakeLists.txt
in the upper level, only./src/geometry/line/CMakeLists.txt
can be changed. - How can I use
<>
to include the absolute path? I.e.,#include <src/geometry/line/line.h>
? The reason of using<>
is from the Canonical CPP Project Structure.