简体   繁体   中英

How to compile a C++ program via Terminal Mac

I have a question on how to compile a C++ program in Terminal Mac. My program has a header file and a main file. I know that I can't compile both the header file and the main file. and just to compile the main file. I also know that I need to create a name for storing the compiled file. Here is my compile command that I used g++ -o execute1 main.cpp and I get this:

Undefined symbols for architecture x86_64:
"add(int, int)", referenced from:
  _main in main-f2nZvj.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

How can I fix this? Any help will be greatly appreciated. If it helps, below is my code for the two files:

add.h:

int add(int x, int y);

main.cpp:

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

int main(){
    using namespace std;
    cout << "The sum of 9 and 9 is " << add(9, 9) << endl;
    return 0;
}

您需要一个实现add()函数的add.cpp文件,然后可以将整个内容编译为:

$ g++ -Wall main.cpp add.cpp -o execute1

This line:

int add(int x, int y);

in your add.h just tells the compiler that somewhere, there's a function called add that takes two integers and returns an integer. Having this and this alone will let the compiler leave you alone when you use this add function in files that #include "add.h" . The compiler doesn't have to know exactly what the function does, it just needs to know what parameters it accepts and what the function returns. It doesn't bother looking for the function body until it actually goes to compile the function.

In order for this to properly compile, you need to include a function body for your add function in add.cpp . Even just this will work:

int add(int x, int y) {
    return 1;
}

This will allow the program to compile because now the compiler know what code it's supposed to execute when it gets to your call to the add function within main .

This will work, as a minimum, as a placeholder until you're ready to actually write the exact logic you want this function to contain. But until this function body exists, you won't be able to compile (unless you remove all the other references to the function).

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