CS253

This file defines the header for each page. An optional "icon" image (I use the textbook):

Replace this with info about this class:

CS253: Problem Solving with C++

Spring 2014

Separate Compilation

Links to the various pages for this class:

Wish I could do this: * Schedule

Separate Compilation

It’s often useful to separate the class interface (*.h) from the class implementation (*.cc):

Example

Foo.h Foo.cc
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

#include <iostream>

class Foo {
  public:
    Foo();
    int get_data() const;
  private:
    double data;
};

std::ostream & operator<<(std::ostream &, const Foo &);

#endif /* FOO_H_INCLUDED */
#include "Foo.h"

using namespace std;

Foo::Foo() : data(42.0) {
}

int Foo::get_data() const {
    return data;
}

ostream &operator<<(ostream &os, const Foo &f) {
    return os << f.get_data();
}

Contents

The *.h file only contains the method declarations (signatures), function declarations (for non-member functions & operators) and declarations of data members. The *.cc file contains the actual code for the methods and functions. Neither one contains main.

Why?

  1. The users of your class are only interested in the interface, not the implementation.
  2. This enables the class to be compiled separately. For example, if the class is part of a product that you sell, you can deliver only Foo.h and Foo.o to your customers. This keeps your implementation source code out of your customer’s hands.

Compilation

Compile the code like this:

    g++ -Wall main.cc Foo.cc

Note that you should not compile the *.h file. That will result in a *.gch (compiled header) file, which will cause no end of trouble. Remove it if you ever find it.

If you do this with a Makefile, make sure to have main.cc also depend upon Foo.h. After all, if you change Foo.h (say, by adding a member variable) then you must recompile main.cc, because the size of Foo has changed.

Modified: 2014-03-04T11:34

User: Guest

Check: HTML CSS
Edit History Source
Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2015 Colorado State University
CS Building