To simplify my code, I make the code snippet below to explain my question:
def.h
#ifndef _DEF_H_
#define _DEF_H_
const char draw[] = "Draw on the canvas:"
#endif
circle.c
#include "def.h"
void draw_circle(void)
{
printf("%s %s", draw, "a circle.");
}
main.c
#include "def.h"
int main(void)
{
printf("%s %s", draw, "nothing.");
}
The problem is that there will be no problem at compile-time but it will probably fail on link-time because of the redefinition of const char array, draw[]
.
How to prevent this problem to share a const char array between two source files gracefully without putting them into a single compilation unit by adding #include"circle.c"
at the top of main.c
?
Is it possible?
You get multiple definition error when linking because, you put the definition of
draw
in a header file. Don't do that. Put only declarations in the header, and put definitions in one.c
file.In you example, put this in a
.c
fileAnd put this in the header: