【问题标题】:Undefined Reference in CLionCLion 中的未定义引用
【发布时间】:2018-09-01 06:53:51
【问题描述】:

我在 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

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

【问题讨论】:

  • 你没有编译链接testclass.cpp
  • 你需要在 testclass.cpp 中定义void testclass::foo() 而不是testclass()。如果这不是点击。从一本好的 c++ 书开始。
  • @dlmeetei 好的,你是对的,我写问题时忘记正确写 testclass::foo()。但这仍然不是我担心的问题。我仍然收到相同的错误消息。顺便说一句,我编辑了问题。

标签: c++ clion undefined-reference


【解决方案1】:

因此,您需要在 cmake 中添加其他标头和来源,而不仅仅是 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% 工作。

【讨论】:

  • 这不应该由IDE自动完成吗?如果我的项目有很多类,那么我是否必须将它们全部手动放入 set() 和 add_executable() 中?
  • 应该是这样,现在当你右键->新建->C/C++ 文件你可以接受自动放置。如果它出错了,无论如何你应该偶尔清理一下cmake
  • 太棒了!非常感谢。
猜你喜欢
  • 2016-08-21
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-12-10
相关资源
最近更新 更多