Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having the same function in multiple c source files

Tags:

c

gcc

I'm having a hard time finding out why i can't have the same function in several C source files. I always thought that i can't access functions in another source file as long as they ain't declared in a header file.

Lets assume i have the following:

main.c -> includes thread1.h & thread2.h

thread1.h -> declares e.g. void * thread1();

thread1.c -> defines void * thread1(){} and defines void lock(){}

thread2.h -> declares e.g. void * thread2();

thread2.c -> defines void * thread2(){} and defines void lock(){}

Now gcc tells me i can't do that!

gcc -pthread -Wall -o executable main.c thread1.c thread2.c

ERROR: multiple definition of `lock'

So my question now is: How can I accomplish what i want?

I don't think that this is meant to be impossible. Otherwise all that C source code available within all the many C libraries would need to be unique. (nah would make no sense, or would it?)

So i thought to myself about 3h ago that there must be a solution. That i must be missing something here.

Well I tried googling it ... but somehow my google skills didn't help me this time. Is there really no way of doing this? Or am I just to stupid to search for it?

Thanks in advance,

leep

like image 349
leep ev8dance Avatar asked Feb 15 '23 12:02

leep ev8dance


1 Answers

You'll need that function lock() to be static.

static void lock() {..}

The reason is that functions with static are not visible outside of the "translation unit". In other (probably wrong) words, the static functions are private to the *.c file. Hence they dont cause linking errors in the linking stage, as you are currently having.

like image 144
UltraInstinct Avatar answered Feb 26 '23 16:02

UltraInstinct