3

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
  • 7,125
  • 4
  • 33
  • 42
  • I had [this question before](http://stackoverflow.com/questions/8594954/repeated-typedefs-invalid-in-c-but-valid-in-c). It's no longer an issue in C11, where this is explicitly allowed. – Kerrek SB Mar 04 '12 at 00:52

3 Answers3

11

By using include guards.

#ifndef ARRAY_H_
#define ARRAY_H_

typedef struct {
    ...
} array;

#endif
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
3

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.

Adam Liss
  • 47,594
  • 12
  • 108
  • 150
  • Names beginning with underscores are reserved for use by the compiler. – Oliver Charlesworth Mar 04 '12 at 00:55
  • 1
    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). – Matteo Italia Mar 04 '12 at 00:57
  • Agreed -- macros are usually all uppercase. I explicitly use lowercase for include guards to reduce the likelihood that they'll conflict with "real" macros. – Adam Liss Mar 04 '12 at 00:59
  • 1
    @AdamLiss: that's why I use the `_INCLUDED` suffix. :) – Matteo Italia Mar 04 '12 at 01:00
2

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

andrewmu
  • 14,276
  • 4
  • 39
  • 37
  • 1
    Indeed. But it's less portable, so you should use include guards. – Oliver Charlesworth Mar 04 '12 at 00:55
  • 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: http://en.wikipedia.org/wiki/Pragma_once – andrewmu Mar 04 '12 at 13:14