Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a variable across multiple source files

Tags:

c

gcc (GCC) 4.7.2
c89

Hello,

I have the following in my service.h file

enum service_state_code {
    NO_ERROR_OK,
    ERROR_INCORRECT_STATE,
    ERROR_EMPTY_STRING,
    ERROR_NO_COMMAND_FOUND
};

const char *service_state_msg[] = {
    "OK:",
    "ERROR: Incorrect state for modifying service channel state",
    "ERROR: No command found",
    "ERROR: No command parameters",
    NULL
};

get_channel_service_state(channel_t *channel, const char *msg);

And I have 2 other *.c files that will include the service.h file.

network.c and socket.c

And I use it something like this:

get_channel_service_state(channel, ss7_service_state_msg[ERROR_INCORRECT_STATE]);

However, I get a linker error complaining about the:

multiple definition of service_state_msg first defined here

I know the reason why I am getting this error. As the service_state_msg is being defined twice as a global in service.h for each time it is included in a *.c file.

I am just asking what is the best way to being about to use service_state_msg across multiple *.c source files?

Many thanks for any suggestions,

like image 926
ant2009 Avatar asked Feb 15 '23 17:02

ant2009


1 Answers

You could make service_state_msg extern in the header file:

extern const char *service_state_msg[];

And then move this:

const char *service_state_msg[] = {
    "OK:",
    "ERROR: Incorrect state for modifying service channel state",
    "ERROR: No command found",
    "ERROR: No command parameters",
    NULL
};

to any one of your C files. Alternatively, you could leave the initialization in the header file but make service_state_msg static:

static const char *service_state_msg[] = {
    "OK:",
    "ERROR: Incorrect state for modifying service channel state",
    "ERROR: No command found",
    "ERROR: No command parameters",
    NULL
};

But be aware that this means every object file will have a copy of the service_state_msg array, and will all need to be recompiled if it changes.

like image 51
James McLaughlin Avatar answered Feb 23 '23 02:02

James McLaughlin