CLion 中的未定义引用

Undefined Reference in CLion

我用 C++ 和 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)

CMakeList.txt 是由 IDE 自动创建的,我没有更改它。 当我尝试 运行 这个简单的程序时,出现以下错误:

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

谁能帮我理解我做错了什么?

因此您需要向您的 cmake 添加其他 headers 和来源,而不仅仅是 main.cpp。 这是一个很好的方法:

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})

在上面 PROJECT_HEADERS 你添加了 *.h 文件的名称,在 PROJECT_SOURCES *.cpp 文件中。它将工作 100%。