How can I share a const char array between two source files gracefully?

1k views Asked by At

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?

2

There are 2 answers

2
Yu Hao On BEST ANSWER

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[];
0
Jens Gustedt On

Unfortunately there are no real named constants in C for such types. The only possibility are macros. For strings you could do

#define draw "Draw on the canvas:"

or if you want to insist that it is const qualified:

#define draw (char const*)"Draw on the canvas:"
#define draw (char const[]){ "Draw on the canvas:" }

The last shows the possibility for other types, use compound literals. Here using const is important, such that the compiler may optimize better.