I am learning Modern C++ form a course by University of Bonn. I have declared a class in a grass.h
file and its implementation in a corresponding grass.cpp
file. Similarly in another tools.h
-tools.cpp
declaration-implementation pair is a function that takes in a reference to the class object defined above. And finally a main.cpp
file initialises a Grass object from first pair and passes it to the function from the second pair. I am able to compile main.cpp
and get the desired output from these command line instructions:
c++ -std=c++11 -g -c grass.cpp -o grass.o
c++ -std=c++11 -g -c tools.cpp -o tools.o
c++ -std=c++11 -g main.cpp grass.o tools.o -o main
but unable to do so with CMake. I do not know what the command line instructions are called (linking and compiling?).
Here is the code example "grass.h":
#include <string>
#pragma once
class Grass
{
private:
int green_;
std::string name_;
public:
Grass(int green, std::string name): green_{green}, name_{name} {}
int get_green() const; // getter functions for
const std::string& get_green_name() const; // both private members
};
The functions just return the values and are implemented in "grass.cpp".
Then I have a "tools.h":
#include <iostream>
#include "grass.h"
#pragma once
void PrintGrass(Grass& grObj);
And this function just prints values from the getter functions of Grass.
Finally, the main.cpp contains:
int main ()
{
Grass grObj{10, "ABC"};
PrintGrass(grObj);
cout << endl;
return 0;
}
The CMake error occurs at 100% Linking CXX executable main. The error is in tools.cpp: undefined reference to `Grass::get_green_name[abi:cxx11]()'
and undefined reference to `Grass::get_green()'
. This means that the the program is unable to find to find the definition of these function, right? The CMake file looks like this:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_BUILD_TYPE Debug)
set(CMAKE_CXX_FLAGS "-Wall")
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0")
add_library(grass grass.cpp)
add_library(tools tools.cpp)
add_executable(main main.cpp)
target_link_libraries(main grass tools)
How do I make this work with CMake? Thank you very much for your help.
Aucun commentaire:
Enregistrer un commentaire