Reputation: 1022
I have the following .h file
#ifndef _EXCEPTION_H
#define _EXCEPTION_H
...
const char* _ErrorCode[] = {
"%s",
"Error: Index is out of range.",
"Error: Stack is empty.",
"Error: New matrix size is not greater than current one.",
"Error: Index or size cannot be negative.",
"Error: Method option is not within permissible options."
"Error: File could not be found or created."
"Error: There was not enough memory to allocate container."
}; // Error code list
...
#endif
that is included by many files. But when i try to compile, i get the following linker error:
4 warnings generated.
duplicate symbol __ErrorCode in:
exception.o
graph.o
duplicate symbol __ErrorCode in:
exception.o
io.o
duplicate symbol __ErrorCode in:
exception.o
list.o
duplicate symbol __ErrorCode in:
exception.o
matrix.o
duplicate symbol __ErrorCode in:
exception.o
stack.o
which means the compiler is redefining the _ErrorCode global variable in all the files in which exception.h is included even though there is an #ifndef at the beginning of the file. How do i stop this from happening? If i can't, how do i define a read-only array of strings that i can print in case of errors like this?
Upvotes: 1
Views: 225
Reputation: 1022
From what i understand the linker doesn't like initializing global variables in .h files because it considers them as re-defined in every instance of the file. The solution is to make
extern const char* _ErrCode[];
then on the .c do
const char* _ErrCode[] = {...}
Upvotes: 0
Reputation: 1576
If you're using #include "exception.h"
in exception.c, graph.c, io.c, and every other C source file in your project, then that's the equivalent of copying the contents of exception.h into the top of every C source file.
That means that in each C source file, there's an _ErrorCode
variable defined. When the object files from each C source file are linked, since __ErrorCode
is defined in each object file, that's a naming conflict.
The solution is to use extern
as Dabo suggests - if you use extern const char* __ErrorCode[];
in the header file, then each object file will know to expect an __ErrorCode
variable defined elsewhere. Then, you can define the variable in exception.c. During linking, the extern
variables will all be resolved to the __ErrorCode
defined in exception.c.
Upvotes: 1