Programming Tutorials

Compiling and Linking Multiple Source Files in C++

By: B. Lippman in C++ Tutorials on 2011-03-18  

To produce an executable file, we must tell the compiler not only where to find our main function but also where to find the definition of the member functions defined by the Sales_item class. Let's assume that we have two files: main.cc, which contains the definition of main, and Sales_item.cc, which contains the Sales_item member functions. We might compile these files as follows:

     $ CC -c main.cc Sales_item.cc # by default generates a.exe
                                   # some compilers generate a.out

     # puts the executable in main.exe
     $ CC -c main.cc Sales_item.cc -o main

where $ is our system prompt and # begins a command-line comment. We can now run the executable file, which will run our main program.

If we have only changed one of our .cc source files, it is more efficient to recompile only the file that actually changed. Most compilers provide a way to separately compile each file. This process usually yields a .o file, where the .o extension implies that the file contains object code.

The compiler lets us link object files together to form an executable. On the system we use, in which the compiler is invoked by a command named CC, we would compile our program as follows:

     $ CC -c main.cc              # generates main.o
     $ CC -c Sales_item.cc        # generates Sales_item.o
     $ CC main.o Sales_item.o     # by default generates a.exe;
                                  # some compilers generate a.out

     # puts the executable in main.exe
     $ CC main.o Sales_item.o -o main

You'll need to check with your compiler's user's guide to understand how to compile and execute programs made up of multiple source files.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)