4

I made a small test project in C++ and in CLion IDE:

main.cpp

#include "testclass.h"

int main() {

    testclass *test = new testclass();
    test->foo();

    return 0;
}

testclass.cpp

#include <iostream>
#include "testclass.h"

using namespace std;

void testclass::foo(){
    cout << "Hello, World!" << endl;
}

testclass.h

class testclass {
public:
    void foo();

};

CMakeLists.txt

cmake_minimum_required(VERSION 3.9)
project(untitled1)

set(CMAKE_CXX_STANDARD 11)

add_executable(untitled1 main.cpp)

The CMakeList.txt is created by the IDE automatically and I haven't changed it. When I try to run this simple program I get the following errors:

CMakeFiles/untitled1.dir/main.cpp.o: In function `main':
/home/irene/CLionProjects/untitled1/main.cpp:7: undefined 
reference to `testclass::foo()'
collect2: error: ld returned 1 exit status

Can someone help me understand what am I doing wrong?

Yhprums
  • 189
  • 1
  • 11
  • 1
    You are not compiling and linking `testclass.cpp` – UnholySheep Mar 22 '18 at 18:17
  • 1
    You need to define `void testclass::foo()` instead of `testclass()` in testclass.cpp. If this is not clicking., start with a good c++ book. – dlmeetei Mar 22 '18 at 18:18
  • @dlmeetei Ok yeah you are right I forgot to write testclass::foo() correctly when I wrote the question. But still this isn't the problem I am afraid. I still get the same error message. I edited the question btw. – Yhprums Mar 22 '18 at 18:26

1 Answers1

2

So you need add to your cmake other headers and sources, not only main.cpp. Here is a nice way to do it:

cmake_minimum_required(VERSION 3.9)
project(untitled1)

set(CMAKE_CXX_STANDARD 11)

set(PROJECT_HEADERS
        testclass.h
        )
set(PROJECT_SOURCES
        main.cpp
        testclass.cpp
        )

add_executable(untitled1 ${PROJECT_SOURCES} ${PROJECT_HEADERS})

In above PROJECT_HEADERS you add names of *.h files, and in PROJECT_SOURCES *.cpp files. It will work for 100%.

  • Shouldn't this be done automatically by the IDE? If my project has many many classes then do I have to put them all manually inside set() and in add_executable()? – Yhprums Mar 22 '18 at 18:48
  • It should be, now when you right click->new->C/C++ file you can accept to put it automatically. And if it's puts wrong, well anyway you should cleans up cmake once in a while – Michał Kalinowski Mar 22 '18 at 18:53
  • Great! Thank you so much. – Yhprums Mar 22 '18 at 18:58