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:
#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.
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
:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.