Typedef in header file that's included multiple times

11,309

Solution 1

By using include guards.

#ifndef ARRAY_H_
#define ARRAY_H_

typedef struct {
    ...
} array;

#endif

Solution 2

The common idiom is to structure your headers like this:

#ifndef array_h_
#define array_h_

// Contents of header file go here

#endif // array_h_

This will prevent the header from being #included more than once.

Solution 3

On some modern compilers using #pragma once at the start of the header file will have the same effect as the include guard idiom.

Share:
11,309

Related videos on Youtube

BraedenP
Author by

BraedenP

Updated on June 18, 2022

Comments

  • BraedenP
    BraedenP almost 2 years

    Basically, I've defined and typedef'ed this struct:

    typedef struct{
        void** elements;
        int numElements;
        int itemSize;
        int capacity;
        int dynamicElements;
    }array;
    

    for which I've written accompanying dynamic array manipulation functions. However, I have a bit of a problem. In various functions, I pass this struct as an argument. In order to modularize the code, I need to prototype these functions in header files (and in order to allow arguments of type array, I need to include "array.h" in these header files themselves.)

    So after including all of my header files, the "array.h" header file has been included multiple times. As would be expected, the struct type has been typedef'ed more than once, and causes conflicts.

    My question is: how can I have this definition in my header file, such that it doesn't break if included multiple times?

  • BraedenP
    BraedenP about 12 years
    Duh! Why didn't I think of that? Perfect.
  • Oliver Charlesworth
    Oliver Charlesworth about 12 years
    Indeed. But it's less portable, so you should use include guards.
  • Oliver Charlesworth
    Oliver Charlesworth about 12 years
    Names beginning with underscores are reserved for use by the compiler.
  • Matteo Italia
    Matteo Italia about 12 years
    Symbols with a leading underscore followed by an uppercase letter or by another underscore are reserved for the implementation in any scope, and symbols with a leading underscore followed by any letter are reserved at file and tag scope (C99 §7.1.3). That being said, usually macros are written all uppercase (I myself use the convention ARRAY_H_INCLUDED for my include guards).
  • Adam Liss
    Adam Liss about 12 years
    Agreed -- macros are usually all uppercase. I explicitly use lowercase for include guards to reduce the likelihood that they'll conflict with "real" macros.
  • Matteo Italia
    Matteo Italia about 12 years
    @AdamLiss: that's why I use the _INCLUDED suffix. :)
  • Blkc
    Blkc about 12 years
    That is true in general, but there are advantages to using #pragma once: including improved compile time efficiency. There is a good discussion of the use here: en.wikipedia.org/wiki/Pragma_once