CS253

CS253: Software Development with C++

Spring 2017

Compiled Header Files

See this page as a slide show

Compiled Header Files

CS253 Compiled Header Files

Simple Example

Consider this simple program. It gets π from a header file:

    % cat main.cc
    #include "pi.h"
    #include <iostream>
    int main() {
        std::cout << pi << '\n';
        return 0;
    }
    % cat pi.h
    constexpr auto pi = 3.14;
    % g++ -Wall main.cc
    % ./a.out
    3.14
    % ls
    a.out  main.cc  pi.h

Note that pi.h is not mentioned in the compile command.

What is we try to compile pi.h?

    % g++ -Wall main.cc pi.h
    % ls
    a.out  main.cc  pi.h  pi.h.gch
    % ./a.out
    3.14
Let’s improve the value of π:
    % echo "constexpr auto pi = 3.14159;" >pi.h
    % g++ -Wall main.cc 
    % ./a.out
    3.14
Hey, why didn’t it work?
    % rm pi.h.gch 
    % g++ -Wall main.cc 
    % ./a.out
    3.14159

Moral of the story

When the compiler sees #include "pi.h", it first looks for pi.h.gch, and uses that precompiled header file if it’s present.

This means that, if you change pi.h, it doesn’t matter, because the compiler uses pi.h.gch if it’s there. Ack!

This can be a powerful tool, if used properly with a well-written Makefile. My attitude: stay away from it.

Modified: 2017-03-26T11:35

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