Sign in with Google to keep private notes

C++ Preprocessor Directives, Functions, and Inline Functions

Preprocessor directives

#include <iostream> versus #include "iostream" will generally include the same standard header file. The difference is that angle brackets direct the compiler to search its configured system include paths, whereas quotation marks typically search locally first, then fall back to system include paths. The precise search rules are implementation-defined.

Don't rely on transitive includes.

Grouping rule:

  1. The paired header file for this code file (e.g. add.cpp should #include "add.h")
  2. Other headers from the same project (e.g. #include "mymath.h")
  3. Third-party library headers (e.g. #include <boost/tuple/tuple.hpp>)
  4. Standard library headers (e.g. #include <iostream>)

Alphabetically sort them within each group.

Header guards

Header guards look like this:

#ifndef SQUARE_H
#define SQUARE_H

int getSquareSides()
{
    return 4;
}

#endif

This is kind of like setting a boolean within a block of code to prevent the guarded content from being included again in the same translation unit.

Note that this prevents redefinitions within a single translation unit, but not between multiple different translation units.

                         square.h
                  +----------------------+
                  | #ifndef SQUARE_H     |
                  | #define SQUARE_H     |
                  |                      |
                  | int getSquareSides() |
                  | { return 4; }        |
                  |                      |
                  | #endif               |
                  +----------+-----------+
                             |
               +-------------+-------------+
               |                           |
               v                           v
           main.cpp                    square.cpp
      #include "square.h"         #include "square.h"
               |                           |
               v                           v
      Is SQUARE_H defined?        Is SQUARE_H defined?
              NO                          NO
               |                           |
      Define SQUARE_H             Define SQUARE_H
      Include function            Include function
               |                           |
               v                           v
       +-------------------+       +-------------------+
       | main.o            |       | square.o          |
       |                   |       |                   |
       | getSquareSides()  |       | getSquareSides()  |
       | { return 4; }     |       | { return 4; }     |
       +---------+---------+       +---------+---------+
                 |                           |
                 +-------------+-------------+
                               |
                               v
                            LINKER
                               |
                               v
                Multiple definitions of getSquareSides()

Functions

  • main() is required to return an int.
  • Explicit function calls to main() are disallowed.
  • It is a common misconception that main is always the first function that executes: global variables may be initialized prior to the execution of main. If the initializer for such a variable invokes a function, then that function will execute prior to main.
  • You can use macros from <cstdlib> to return a specific exit code:
#include <cstdlib> // for EXIT_SUCCESS and EXIT_FAILURE

int main()
{
    return EXIT_SUCCESS;
}

Default arguments are evaluated every time a function is called, so the below program prints a twice.

int goon() {
    cout << 'a' << endl;
    return 1;
}

void bar([[maybe_unused]] int i = goon()) { }

int main() {
    bar();
    bar();
}

Inline Functions

Inline expansion can help us avoid function-call overhead when that overhead is a significant proportion of runtime. We get to reap the benefits of function readability without the call overhead.

When to use inline expansion for performance: When removal of the function-call overhead outweighs the cost of a larger executable.

However, inline expansion has its own potential cost: if the body of the function being expanded takes more instructions than the function call being replaced, then each inline expansion will cause the executable to grow larger. Larger executables tend to be slower (due to not fitting as well in memory caches).

(Unless expanding into two different functions means they no longer belong in the same cache line. Because they're no longer "the same instruction" stored at "the same address" for the same instruction cache.)

The most common kind of function that can't be expanded inline without additional whole-program optimization is a function whose definition is in another translation unit. Since the compiler can't see the definition, it doesn't know what to replace the function call with!

Also note that you can't really control inline expansion by using inline anymore because inlining ought to be decided on a call-by-call basis, and there is no standard C++ syntax that reliably instructs the compiler to inline or not inline a particular call.

(This all reminds me of the Karl Cook talk I watched a few months back: YouTube talk.)

Inline nowadays

Basically the use of the keyword changed over time. Originally inline was a performance hint, intended to allow inline expansion during compilation. That meant the definition had to be available in every translation unit that used it so the compiler (which normally cannot see functions between translation units) would know the beginning, middle, and end of the function it was inline-expanding.

Copying the same definition over and over would ordinarily violate the One Definition Rule (ODR), so C++ allows multiple identical definitions of inline functions across translation units. And people started to use this, I think. For what, I honestly don't know.

  • The definition of an inline function must be reachable in every translation unit where it is odr-used (a forward declaration alone will not suffice). Only one such definition can occur per translation unit, otherwise a compilation error will occur.
  • A definition can occur after an earlier use with a suitable declaration, but the exact requirements depend on whether the function is declared inline at that point. The compiler may also have limited opportunities for inline expansion before it has seen the body.
  • Every definition of an inline function with external linkage (which ordinary free functions have by default) must satisfy the ODR's requirements, including matching definitions, otherwise the program is ill-formed, no diagnostic required.

Inline functions are typically defined in header files, where they can be #included into any code file that needs to see the full definition of the identifier. This helps ensure that all inline definitions for an identifier are identical.

pi.h:

#ifndef PI_H
#define PI_H

inline double pi() { return 3.14159; }

#endif

main.cpp:

#include "pi.h" // will include a copy of pi() here
#include <iostream>

double circumference(double radius); // forward declaration

int main()
{
    std::cout << pi() << '\n';
    std::cout << circumference(2.0) << '\n';

    return 0;
}

Implicitly Inline Functions

  • Functions defined inside a class, struct, or union type definition (14.3 — Member functions), unless attached to a named module.
  • constexpr / consteval functions (F.1 — Constexpr functions).
  • Function template specializations instantiated from function templates (11.7 — Function template instantiation) are generally permitted multiple identical definitions under the ODR; this is not the same thing as every such specialization being implicitly declared inline.

Articles to read next