简体   繁体   English

错误 - “(。text + 0x0):'method'的多重定义”(C程序)

[英]error - “(.text+0x0): multiple definition of 'method' ” (C program)

I currently have 2 C-programs and 1 header file that I have to make into a Makefile. 我目前有2个C程序和1个头文件,我必须在Makefile中。 I am new to compiling programs into Makefiles but I know the basics. 我是新手将程序编译成Makefile,但我知道基础知识。 I type in: 我输入:

cc -c file1.c

cc -c file2.c

cc file1.o file2.o

----- I get the following error ----- -----我收到以下错误-----

file2.o: In function 'method':

file2.c:(.text+0x0): multiple definition of 'method'

file1.o:file1.c:(.text+0x0): first defined here

collect2: ld returned 1 exit status

What is the problem? 问题是什么? I heard various things like because they share the same header ('method' is defined in the header file) that the compiler thinks there is two of them. 我听到了各种各样的事情,比如因为它们共享相同的头文件(头文件中定义了'方法'),编译器认为它们有两个。 I don't know. 我不知道。 What do you guys think? 你们有什么感想?

Thank you, 谢谢,

EDIT: Thank you for the responses. 编辑:谢谢你的回复。 What if 'method' is a "struct" function? 如果'method'是“struct”函数怎么办? Would it still be a good idea to just move it to somewhere else? 将它移到其他地方仍然是个好主意吗? I just tried it and now I'm getting a "dereferencing pointer to incomplete type". 我刚试了一下,现在我得到了一个“解除指向不完整类型的指针”。

'method' is defined in the header file. 'method'在头文件中定义。

You should not be doing that. 你不应该这样做。 If you do that the function definition will go into all the files that include the header which causes linking errors as there will be multiple versions of the method. 如果你这样做,函数定义将进入包含导致链接错误的标题的所有文件,因为将有多个版本的方法。

You need to only declare the method in a header file. 您只需要在头文件中声明该方法。 Define it in a .c file, compile it and link it to the object file from where this function is getting called. .c文件中定义它,编译它并将其链接到调用此函数的目标文件。

If method is a small function defined in a header file, you should declare it static inline eg like 如果method是头文件中定义的小函数,则应该将其声明为static inline例如

/// in header.h
static inline int sum(int x, int y) { return x+y; }

Make your header file like this (the ifndef is to make sure it doesnt get included more than once): 像这样制作你的头文件(ifndef是为了确保它不会被包含多次):

#ifndef MYHEADER_H_
#define MYHEADER_H_

extern void mymethod1(void); // only put declaration in headers
extern void mymethod2(void);
... other stuff

#endif

You have definition for method in both file2.c and file1.c . 您在file2.c和file1.c中都有方法的定义。 Try to only put declaration in common header files and move definition to only one c file. 尝试仅将声明放在公共头文件中,并将定义移动到只有一个c文件。

将函数声明为静态函数。

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

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