简体   繁体   中英

Typedef in header file that's included multiple times

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?

By using include guards .

#ifndef ARRAY_H_
#define ARRAY_H_

typedef struct {
    ...
} array;

#endif

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.

在一些在头文件开头使用#pragma once现代编译器将具有与包含保护惯用法相同的效果。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM