1

I have a curious case of the "undefined symbol for architecture", which admittedly has been asked here numerous times but I feel the reason behind my error is more fundamental.

I am new to C++ and have a very basic program using no third party libraries, hence I do not understand why it would be, as other answers to this question have alluded, related to a mixture of libraries built with different compilers.

Here is my code in it's entirety

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)

In build I run

cmake ../src
make

This worked fine before I started using the Point3D class inside main but now I see the error

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

Have I written the class implementation wrong for Point3D?

I'm running this on OS X Sierra with make 3.81.

clicky
  • 865
  • 2
  • 14
  • 31

1 Answers1

1

In your CMakeLists.txt, you need to also add Point3D.cpp to the list of add_executable sources:

add_executable(myTest myTest.cpp Point3D.cpp)
Stuart Berg
  • 17,026
  • 12
  • 67
  • 99
  • this worked! thank you. is there a way to reference all files in a dir, if I end up with lots of classes. – clicky Apr 09 '17 at 14:50
  • 1
    I don't do that in my own projects, but this post seems to have some reasonable suggestions: http://stackoverflow.com/questions/2110795/how-to-find-all-c-files-for-cmake-build-system – Stuart Berg Apr 09 '17 at 14:55