简体   繁体   English

在多个c源文件中具有相同的功能

[英]having the same function in multiple c source files

I'm having a hard time finding out why i can't have the same function in several C source files. 我很难找到为什么我不能在几个C源文件中拥有相同的功能。 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 main.c - >包括thread1.h和thread2.h

thread1.h -> declares eg void * thread1(); thread1.h - >声明例如void * thread1();

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

thread2.h -> declares eg void * thread2(); thread2.h - >声明例如void * thread2();

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

Now gcc tells me i can't do that! 现在gcc告诉我,我不能那样做!

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

ERROR: multiple definition of `lock' 错误:`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. 否则,所有许多C库中可用的所有C源代码都需要是唯一的。 (nah would make no sense, or would it?) (没有意义,或者不会?)

So i thought to myself about 3h ago that there must be a solution. 所以我在3小时前想到自己必须有一个解决方案。 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 LEEP

You'll need that function lock() to be static . 你需要将函数lock()设置为static

static void lock() {..}

The reason is that functions with static are not visible outside of the "translation unit". 原因是具有static函数在“翻译单元”之外是不可见的。 In other (probably wrong) words, the static functions are private to the *.c file. 在其他(可能是错误的)单词中,静态函数对* .c文件是私有的。 Hence they dont cause linking errors in the linking stage, as you are currently having. 因此,它们不会像您当前那样在链接阶段导致链接错误。

You must declare lock as static void lock(){} . 您必须将lock声明为static void lock(){}

Otherwise the function name will be visible all over the program and you'll get a name collision (although you still won't be able to call it without a function prototype). 否则函数名称将在整个程序中可见,并且您将获得名称冲突(尽管如果没有函数原型,您仍然无法调用它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM