1234
1234

Reputation: 579

Compile Simple C++ class with unexpected errors on my Mac OSX El Capitan

My Class file: Mylib.h

class myclass {
    public:
        myclass();
    public:
        void fun();
};

My header file: Mylib.cpp

myclass::myclass() {
}
void myclass::fun() {
    std::cout<<"fun"<<std::endl;
}

My Main file: try.cpp

#include<iostream>
#include "Mylib.h"

using namespace std;

int main() {
    std::cout<<"cool"<<std::endl;
    myclass myobj;
}

I compile try.cpp in my Mac OSX El Captitan (10.11.4)

g++ -o try try.cpp

I got following errors:

g++ -o try try.cpp 
Undefined symbols for architecture x86_64:
  "myclass::myclass()", referenced from:
      _main in try-f5efba.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here is g++ info on my Mac OSX

g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.29)
Target: x86_64-apple-darwin15.4.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Upvotes: 0

Views: 94

Answers (1)

AndreLDM
AndreLDM

Reputation: 2198

This code won't compile with any compiler. First Mylib.h has the class implementation and Mylib.cpp has the class definition. Here is the working code (a bit modified):

Mylib.cpp

#include<iostream>
#include "Mylib.h"

MyClass::MyClass() { }
void MyClass::fun() {
    std::cout << "fun" << std::endl;
}

Mylib.h

class MyClass {
    public:
        MyClass();
        void fun();
};

try.cpp

#include<iostream>
#include "Mylib.h"

int main() {
    std::cout<<"cool"<<std::endl;
    MyClass myobj;
    myobj.fun();
}

Compile with: g++ -o try try.cpp Mylib.cpp

Upvotes: 2

Related Questions