全局变量的多重定义 [英] Multiple definition of a global variable
本文介绍了全局变量的多重定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
常量变量在标题中不起作用
Possible Duplicate:
constant variables not working in header
在用于创建共享库的头文件中,具有以下内容:
In my header file which I use to create a shared object, I have the following:
#ifndef LIB_HECA_DEF_H_
#define LIB_HECA_DEF_H_
struct dsm_config {
int auto_unmap;
int enable_copy_on_access;
};
enum { NO_AUTO_UNMAP, AUTO_UNMAP } unmap_flag;
enum { NO_ENABLE_COA, ENABLE_COA } coa_flag;
const struct dsm_config DEFAULT_DSM_CONFIG = { AUTO_UNMAP, NO_ENABLE_COA };
<more code ...>
#endif
编译时,出现以下错误:
When I compile, I get the following error:
cc -g -Wall -pthread libheca.c dsm_init.c -DDEBUG master.c -o master
/tmp/cciBnGer.o:(.rodata+0x0): multiple definition of `DEFAULT_DSM_CONFIG'
/tmp/cckveWVO.o:(.rodata+0x0): first defined here
collect2: ld returned 1 exit status
make: *** [master] Error 1
有什么想法吗?
推荐答案
由于实现文件文件中的每个include,都会创建一个新的struct实例(并将其存储在目标文件中).
Because with every include in a implementation file file, a new instance of your struct is created (and stored in the object file).
为避免这种情况,只需在头文件中将结构声明为"extern",然后在实现文件中对其进行初始化:
To avoid this, just declare the struct as "extern" in the header file and initialize it in the implementation file:
// In your header file:
extern const struct dsm_config DEFAULT_DSM_CONFIG;
// In your *.c file:
const struct dsm_config DEFAULT_DSM_CONFIG = { AUTO_UNMAP, NO_ENABLE_COA };
这将解决您的问题.
这篇关于全局变量的多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文