简体   繁体   中英

Linking c++ files using CMakeLists.txt

Okay, so I just started dabbing into c++ and I'm hoping to get ahead on my classes in the fall but instead of using the a compiler I've been using nitrous.io as an IDE. Anyways long story short, I'm using CMakeLists.txt to compile and run but I've been running into a lot of difficulties when trying to link together an interface, it's corresponding cpp file and a main function.

Gradebook.h

//Gradebook.h
 #include <string>
 using namespace std;

class Gradebook
{
  public:
    Gradebook(string n);
    Gradebook();
    void setCourse(string n);
    string getCourse();
    void displayMessage();

  private:
    string course;
}; 

Gradebook.cpp

//Gradebook.cpp
#include "Gradebook.h"
#include <iostream>
using namespace std;

Gradebook::Gradebook(string n)
{
  course = n;
} 

Gradebook::Gradebook()
{
  cout << "Default constructor used." << endl;
} 

void Gradebook::setCourse(string n)
{
  course = n;
}

string Gradebook::getCourse()
{
  return course;
}

void Gradebook::displayMessage()
{
  cout << "Welcome to " << course << "'s gradebook." << endl;
}

GradebookRunner.cpp - main function

#include "Gradebook.h"

int main()
{
  Gradebook g("Intro to c++");
  g.displayMessage();
  return 0;
}  

CMakeLists.txt - I'm 95% sure that the syntax and linking is done correctly in the .h and .cpp files, this is where I believe I'm making the mistake.

##I've tried to use different combinations of Gradebook and Gradebook.cpp in here.

cmake_minimum_required(VERSION 2.6)
project(Gradebook)
add_executable(Gradebook Gradebook.cpp)

Any help will be much appreciated :D

Simply add all files that belong to the executable (both headers and source files, so you have them all in IDE and dependencies are correctly resolved by CMake).

  add_executable(Gradebook Gradebook.cpp GradebookRunner.cpp Gradebook.h)

Note that GLOB feature could be tricky.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM