| | | | | |

Compiling a Multi-File Program

  • Compiling a Two File Program (.h and .cpp)
    • Use the -I flag to find any #include files that are not part of the language
    • g++ -o <execname> -I. <filename>.cpp compiles a file filename.cpp, which includes the filefile.h #include  into an executable named execname
    • The '.' that appears after the -I stands for the current working directory
  • Compiling a Multi-File Program
    • Example files:
    • // file1.h
      const int magic_number = 1492;
      long multiply_by_MN (int number);
      
      // file1.cpp
      #include <file1.h>
      long multiply_by_MN (int number) {
        return (long)(number * magic_number);
      }
      
      // main.h
      constant int loop_n_times = 4;
      
      // main.cpp
      #include <iostream.h>
      #include <file1.h>
      #inlcude <main.h>
      int main() {
        // includes a call to multiply_by_MN()
        // uses constant magic_number
      }
      
    • g++ -c -I. file1.cpp creates the object code file file1.o, for the file file1.cpp
    • g++ -c -I. main.cpp creates the object code file main.o, for the file main.cpp
    • g++ -o <execname> main.o file1.o creates an executable by linking the object code for main.o, file.o, and any default libraries together

| | Top of Page | A. The G++ Compiler - 3 of 4