简体   繁体   中英

C++ Can't compile simple class header (linker command failed with exit code 1)

the problem seems to be with the compiler I'm using though I'm fairly new to programming so I'm not sure how to mess with that(I'm using VSCode on Mac OSX)

This is my header:

#ifndef STICKMAN_H
#define STICKMAN_H

class Stickman{
public:
Stickman();
};
#endif

This is my source file:

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

using namespace std;

Stickman::Stickman(){
    cout << "Hello\n";
}

This is my main:

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

int main(){
   Stickman figure;
}

This is the ERROR message in the terminal:

Alexandres-MBP:Game alexandrecarqueja$ cd
"/Users/alexandrecarqueja/Desktop/Game/" && g++ main.cpp -o main && "/Users/alexandrecarqueja/Desktop/Game/"main
Undefined symbols for architecture x86_64:
"Stickman::Stickman()", referenced from:
 _main in main-d38641.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

You need to call this instead:

g++ main.cpp stickman.cpp -o main

which will also compile stickman.cpp . Then the linker will know what to do. Right now you have a #include stickman.h in your main which declares the class, but does not define it.

The linker sees a constructor is declared (in stickman.h ), but does not see how it is implemented ( stickman.cpp was not compiled). Hence it is not able to link with the constructor body.

It must be compiler specific because I ran the code in Visual Studio and it built successfully. I would suggest you get the free express/community Visual Studio 2017 IDE software if you happen to have a Windows computer. The code looks fine so I'm personally unsure of what may be causing your issue if it's not compiler related. If you only have a Mac computer, then I suggest maybe looking into other free compilers.

You also receive this error in vscode if your project has a path that includes spaces. As mentioned above you also need to compile all your cpp-files.

To do this in vscode in eg macOS Catalina please see my answer here https://stackoverflow.com/a/61331301/1071899

Basically you need to make a tasks.json file with the compiler specific flags. Here you need to include that all *.cpp files should be compiled AND you need to escape the whitespaces by adding "\\"${workspaceFolder}\\"/*.cpp", instead of "${file}", . Take note of the two \\" . This will make sure that your project path is surrounded by "" and it will not complain about linker errors.

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.

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