
writer:lIcht email:lIcht.gzl@gmail.com date: 2019.10.6
出现原因:使用sublime3学习c++时面向对象时出现的编译错误,编译方式为macos终端命令行使用g++实现编译运行。
error内容:
xUndefined symbols for architecture x86_64:"_main", referenced from:implicit entry/start for main executableld: symbol(s) not found for architecture x86_64clang: error: linker command failed with exit code 1 (use -v to see invocation)[Finished in 0.4s with exit code 1]
代码:
main.cpp:
xxxxxxxxxxusing namespace std;int main(int argc, char const *argv[]){ Student stu1; Student stu2(5); Student stu3("sda", "asdiisd") return 0;}Student.h:
using namespace std;class Student{ public: Student(); Student(int); Student(string, string); ~Student(); void ShowInfo(); string GatName() {return m_Name; } void SetName(string val) {m_Name = val; } string Getdesc() {return m_desc; } void Setdesc(string val) {m_desc = val; } int Getage() {return m_age; } void Setage(int val) { if(val < 0){ m_age = 18; }else{ m_age = val; } } protected: private: string m_Name; string m_desc; int m_age;};// STUDENT_HStudent.cpp:
Student::Student(){ cout << "默认构造" << endl;}Student::Student(int age){ Setage(age); cout << "调用带参构造 Student::Student(int age)" << endl;}Student::Student(string name, string desc)//赋值,初始化参数列表的写法{ SetName(name); Setdesc(desc); cout << "调用带参构造 Student::Student(string name, string desc)" << endl;}Student::~Student(){ cout << "该对象被释放" << endl;}
解决方法1:简单方法:将main.cpp中引用的头文件名称:#include "Student.h"改为:#include "Student.cpp"。
解决方法2:在sublime3中使用cltr+b运行main.cpp时是只会编译main.cpp的执行文件的,没有链接和编译Student.cpp的可执行文件,这时需要手动进行创建Student.cpp的可执行文件,输入如下代码行:g++ main.cpp Student.cpp -o Student。
解决成果:
xxxxxxxxxx默认构造调用带参构造 Student::Student(int age)调用带参构造 Student::Student(string name, string desc)该对象被释放该对象被释放该对象被释放[Finished in 0.4s]