Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

c99

c11

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?

like image 517
Kevin Dong Avatar asked Nov 28 '25 11:11

Kevin Dong


1 Answers

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[];
like image 167
Yu Hao Avatar answered Dec 01 '25 02:12

Yu Hao