简体   繁体   English

C ++,Xcode,头文件的链接器错误

[英]C++, Xcode, linker error with header file

I'm learning C++ using Xcode however I always get a linker error when I try to initialize a class in a header file. 我正在使用Xcode学习C ++,但是当我尝试在头文件中初始化类时,总是收到链接器错误。 Here is main.cpp: 这是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 ... 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. 我知道Xcode正在读取main.h,因为我曾经遇到“找不到文件”错误(以及其他错误),但我修复了所有这些错误,不再得到这些错误。 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无法从这2个文件构建机器代码,因为如果我仅将所有代码复制/粘贴到一个文件中,它将起作用。

I was able to get this to build and run, both from the command line: 我能够通过命令行来构建和运行它:

% clang++ main.cpp
% ./a.out
20

and from XCode. 和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,它想在项目中找到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. 如果那不是您的问题,那么我对您没有其他建议,希望其他人也可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM