Variable declaration in multiple source files

gcc (GCC) 4.7.2 c89 

Hello,

My service.h file has the following:

 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 more * .c files that will contain 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:

 multiple definition of service_state_msg first defined here 

I know the reason why I get this error. Since service_state_msg defined twice as global in service.h, each time it is included in the * .c file.

I'm just asking, what is the best way to use service_state_msg across multiple * .c source files?

Thanks so much for any suggestions,

+4
source share
2 answers

You can 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 }; 

for any of your C files. Alternatively, you can leave the initialization in the header file, but do 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 keep in mind that this means that every object file will have a copy of the service_state_msg array, and all of it will need to be recompiled if it changes.

+7
source

Define and initialize in .C file. Use the following command in the header file.

 extern char ** service_state_msg; // in the header file 
+1
source

Source: https://habr.com/ru/post/1494699/


All Articles