CLion中C++项目实验室可运行,本地报undefined reference错误排查
C++未定义引用错误解决:Element构造函数链接失败
项目信息
- 项目名称:graph-puzzle-game-halil-nebioglu
- 目录结构:
graph-puzzle-game-halil-nebioglu/src/CMakeLists.txt graph-puzzle-game-halil-nebioglu/src/main.cpp graph-puzzle-game-halil-nebioglu/src/Array/Element.h graph-puzzle-game-halil-nebioglu/src/Array/Element.cpp
注:Array目录来自另一个Git项目DataStructures-CPP,实验室电脑可正常运行,本地拉取代码后编译报错。
代码文件
CMakeLists.txt
cmake_minimum_required(VERSION 3.23) project(graph-puzzle-game-halil-nebioglu) set(CMAKE_CXX_STANDARD 17) add_executable(graph-puzzle-game-halil-nebioglu main.cpp Array/Element.cpp Array/Element.h )
main.cpp
#include <iostream> #include "Array/Element.h" using namespace array; using namespace std; int main(){ cout<<"test"; Element e = Element(); return 0; }
Element.cpp
#include "Element.h" namespace array { Element::Element(int data) { this->data = data; } int Element::getData() { return data; } Element::Element() { } }
Element.h
#ifndef DATASTRUCTURES_CPP_ELEMENT_H #define DATASTRUCTURES_CPP_ELEMENT_H namespace array { class Element { private: int data; public: Element(); explicit Element(int data); int getData(); }; } #endif //DATASTRUCTURES_CPP_ELEMENT_H
编译错误信息
运行main.cpp时触发链接错误:
g++.exe C:\Users\Halil\CLionProjects\graph-puzzle-game-halil-nebioglu\src\main.cpp -o main C:\Program Files\JetBrains\CLion 2023.2.2\bin\mingw\bin/ld.exe: C:\Users\Halil\AppData\Local\Temp\cc9E8RP8.o:main.cpp:(.text+0x2e): undefined reference to `array::Element::Element()' collect2.exe: error: ld returned 1 exit status
注:移除代码中的Element e = Element();语句后,程序可正常打印"test";保留该语句则编译失败。
解决方案
问题出在CLion的运行配置类型错误:当前使用的是C/C++ File配置,而非CMake Application配置。
修改操作:
- 切换运行配置为CMake Application
- 选择目标为项目名称
graph-puzzle-game-halil-nebioglu,该目标对应CMakeLists.txt中add_executable节点定义的可执行文件。
内容的提问来源于stack exchange,提问作者Halil Nebioğlu
相关产品推荐
相关产品推荐

