编译Simple C ++类,在我的Mac OSX El Capitan上出现意外错误

时间:2016-05-02 23:17:01

标签: c++ compilation clang

我的班级档案: Mylib.h

<add key="editMode" value="2" />
<add key="fileType" value="0" />
<add key="Editor" value="C:\Program Files\Adobe\Adobe Photoshop CC 2015\Photoshop.exe" />

我的标题文件: Mylib.cpp

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

我的主文件:try.cpp

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

我在Mac OSX El Captitan(10.11.4)中编译try.cpp

g ++ -o try try.cpp

我收到了以下错误:

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

using namespace std;

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

这是我的Mac OSX上的g ++信息

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)

1 个答案:

答案 0 :(得分:2)

此代码不会使用任何编译器进行编译。第一个Mylib.h有类实现,Mylib.cpp有类定义。这是工作代码(有点修改):

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();
}

编译:{{1​​}}