How to compile a C++ program via Terminal Mac

24,752

You need an add.cpp file that implements your add() function, then you can compile the whole thing as:

$ g++ -Wall main.cpp add.cpp -o execute1
Share:
24,752
user2967353
Author by

user2967353

Updated on July 06, 2022

Comments

  • user2967353
    user2967353 almost 2 years

    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;
    }
    
    • Paul R
      Paul R over 10 years
      Do you have an add.cpp somewhere ?
    • Paul R
      Paul R over 10 years
      @bamboon: not true - gcc/g++ have symbolic links to their more modern counterparts these days.
    • Admin
      Admin over 10 years
    • nhgrif
      nhgrif over 10 years
      If it helps, below is my code for the two files .... and where is add.cpp?
    • Stephan Dollberg
      Stephan Dollberg over 10 years
      @PaulR Sorry for deleting my comment. I first entered "g++" in a ssh session and thought you were right. Do you have any source for your claim? My g++ is still 4.2. To restate what I said, I claimed that mac osx ships with gcc 4.2 and that one shall use clang.
    • Paul R
      Paul R over 10 years
      @bamboon: you may need to install the CLT package for whatever version of Xcode you are using - with Xcode 5 I get the following for g++ -v: Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
    • Stephan Dollberg
      Stephan Dollberg over 10 years
      @PaulR So it was a misunderstanding, I thought you meant that mac osx ships with e.g.: 4.8. gcc seems to be a symlink to clang which is configured to use gcc 4.2 include dir.