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
Any ideas why?
Because with every include in a implementation file file, a new instance of your struct is created (and stored in the object file).
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 };
This will solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With