user2261693
user2261693

Reputation: 405

How to compile C++ program by command line on Mac

I used to use Xcode to build and run C++ program.

I use command line to compile the same source code in my Xcode project.

Compiling a individual .cpp file is OK.

Compiling more complicated project(more than one file) is NOT OK.

I have tried gcc, g++, clang, clang++.

The main problem is undefined symbol.

Could you show how to compile complicated project (more than one file) by command line?

Upvotes: 4

Views: 19188

Answers (1)

Carl Norum
Carl Norum

Reputation: 224914

From your description, it sounds like you're not using the -c (compile, but don't link) flag. Steps to build your project:

  1. Compile all of the source files:

    c++ -c file1.cpp
    c++ -c file2.cpp
    c++ -c file3.cpp
    
  2. Link your final executable:

    c++ file1.o file2.o file3.o
    

    You can use an optional -o flag to specify the output program name. It probably defaults to a.out.

It would be better to use some kind of build tool (like make, for example) to automate this process, or you'll find it to be very error prone.

Upvotes: 4

Related Questions