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 file
const char draw[] = "Draw on the canvas:"
And put this in the header:
extern const char draw[];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With