体系结构错误的未定义符号

Undefined symbol for architecture error

本文关键字:符号 未定义 错误 体系结构      更新时间:2023-10-16

我有一个奇怪的"建筑未定义符号"的例子,诚然,这里已经问过很多次了,但我觉得我的错误背后的原因更根本。

我是C++新手,并且有一个不使用第三方库的非常基本的程序,因此我不明白为什么它会像这个问题的其他答案所暗示的那样,与使用不同编译器构建的库混合有关。

这是我完整的代码

src/myTest.cpp

#include <iostream>
#include "Point3D.h"
using namespace std;
using namespace lspsm;
int main(int argc, char** argv) {
    Point3D p(1,2,3);
    cout << p.getX() << endl;
    return 0;
}

src/Point3D.h

#ifndef Point3D_H
#define Point3D_H
namespace lspsm {
class Point3D {
    int p_values [3];
public:
    Point3D(int x, int y, int z);
    int getX();
    int getY();
    int getZ();
};
}
#endif

src/Point3D.cpp

#include Point3D_H
namespace lspsm {
Point3D::Point3D(int x, int y, int z) {
    p_values[0] = x;
    p_values[1] = y;
    p_values[2] = z;
}
int Point3D::getX() {
    return p_values[0];
}
int Point3D::getY() {
    return p_values[1];
}
int Point3D::getZ() {
    return p_values[2];
}
}

src/CMakeLists.txt

add_executable(myTest myTest.cpp)

构建中我运行

cmake ../src
make

在我开始使用main中的 Point3D 类之前,这工作正常,但现在我看到了错误

-- Configuring done
-- Generating done
-- Build files have been written to: /Users/mh/dev/CPP/build
[ 50%] Linking CXX executable myTest
Undefined symbols for architecture x86_64:
  "lspsm::Point3D::getX()", referenced from:
      _main in myTest.o
  "lspsm::Point3D::Point3D(int, int, int)", referenced from:
      _main in myTest.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我是否为Point3D写错了类实现?

我正在OS X Sierra上运行它,制作3.81。

CMakeLists.txt中,您还需要将Point3D.cpp添加到add_executable源列表中:

add_executable(myTest myTest.cpp Point3D.cpp)