Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple definition of a global variable [duplicate]

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?

like image 922
Steve Walsh Avatar asked Jan 25 '13 16:01

Steve Walsh


1 Answers

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.

like image 56
junix Avatar answered Sep 16 '22 19:09

junix