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.)
为此,我编写了相应的动态数组操作函数。然而,我有一点问题。在不同的函数中,我将这个结构作为参数传递。为了模块化代码,我需要在头文件中原型化这些函数(为了允许类型数组的参数,我需要包含“array”。h“在这些头文件中。)
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?
我的问题是:如何在头文件中包含这个定义,使它在包含多次后不会中断?
3 个解决方案
#1
10
By using include guards.
通过使用包括警卫。
#ifndef ARRAY_H_
#define ARRAY_H_
typedef struct {
...
} array;
#endif
#2
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.
这将防止标头不止一次被包含在#中。
#3
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.
在一些现代编译器中,在头文件的开头使用#pragma一次将会产生与include保护习惯用法相同的效果。
#1
10
By using include guards.
通过使用包括警卫。
#ifndef ARRAY_H_
#define ARRAY_H_
typedef struct {
...
} array;
#endif
#2
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.
这将防止标头不止一次被包含在#中。
#3
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.
在一些现代编译器中,在头文件的开头使用#pragma一次将会产生与include保护习惯用法相同的效果。