I'm learning C++ using Xcode however I always get a linker error when I try to initialize a class in a header file. Here is main.cpp:
我正在使用Xcode学习C ++,但是当我尝试初始化头文件中的类时,我总是遇到链接器错误。这是main.cpp:
#include <iostream>
#include <fstream>
#include "main.h"
using namespace std;
int main() {
Rectangle rect(4, 5);
cout << rect.area() << endl;
return 0;
}
and main.h
...
#ifndef main_h
#define main_h
using namespace std;
class Rectangle {
int width,height;
public:
Rectangle(int,int);
int area() {return width*height;}
};
Rectangle::Rectangle (int x, int y) { width=x; height=y; }
#endif /* main_h */
..and the linker error
..和链接器错误
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I know Xcode is reading main.h because I used to get a "file not found" error (as well a bunch of others) but I fixed all of that and no longer get those errors. From what I understand Xcode is not able to build the machine code from these 2 files for some reason because if I just copy/paste all the code into one file it does work.
我知道Xcode正在读取main.h,因为我曾经得到一个“找不到文件”错误(以及其他一些错误),但我修复了所有这些并且不再得到那些错误。根据我的理解,Xcode由于某种原因无法从这两个文件构建机器代码,因为如果我只是将所有代码复制/粘贴到一个文件中,它确实有效。
1 个解决方案
#1
0
I was able to get this to build and run, both from the command line:
我可以从命令行获得这个来构建和运行:
% clang++ main.cpp
% ./a.out
20
and from XCode. With XCode, it wants to find your main.h
as part of the project, so it should show up in the project directory next to main.cpp
:
并从XCode。使用XCode,它想要找到你的main.h作为项目的一部分,所以它应该显示在main.cpp旁边的项目目录中:
You can just drag the file into the project. If that's not your issue, than I don't have any other suggestions for you, hopefully others do.
您只需将文件拖入项目即可。如果这不是你的问题,那么我没有其他任何建议,希望其他人也这样做。
#1
0
I was able to get this to build and run, both from the command line:
我可以从命令行获得这个来构建和运行:
% clang++ main.cpp
% ./a.out
20
and from XCode. With XCode, it wants to find your main.h
as part of the project, so it should show up in the project directory next to main.cpp
:
并从XCode。使用XCode,它想要找到你的main.h作为项目的一部分,所以它应该显示在main.cpp旁边的项目目录中:
You can just drag the file into the project. If that's not your issue, than I don't have any other suggestions for you, hopefully others do.
您只需将文件拖入项目即可。如果这不是你的问题,那么我没有其他任何建议,希望其他人也这样做。