简体   繁体   English

多个定义collect2:错误:ld在C中返回了1个退出状态

[英]Multiple definition collect2: error: ld returned 1 exit status in C

Process_struct.h //header file Process_struct.h //头文件

#define MAX_PROCS 5
#define EXIT 1
#define TRUE 1
/*******************************/
FILE *file=NULL;
/*******************************/
static FILE *outLog=NULL;
pthread_t producer;//Producer Thread ID
pthread_t consumer[MAX_PROCS];//consumer thread ID

This is the error I get when I go to run my Makefile: 这是我运行我的Makefile时遇到的错误:

    /tmp/ccvDJUQI.o:(.bss+0x8): multiple definition of `file'
    /tmp/cc4RWdZ4.o:(.bss+0x8): first defined here
    collect2: error: ld returned 1 exit status
    make: *** [Multiprocessor] Error 1

The build tells me that I have multiple definition of file in my program. 该版本告诉我程序中有多个file定义。 Well the only section that I'm calling my file is in my header file. 好吧,我称呼我的文件的唯一部分是在我的头文件中。 With my header file code above, there is no multiple definition of file in the file. 通过上面的头文件代码, file中没有file多个定义。 The file is used throughout both of my .c program files but is only appears in my header file as a variable. file在我的两个.c程序文件中都使用过,但仅在我的头文件中作为变量出现。 I'm not sure why this error appears. 我不确定为什么会出现此错误。 Can anyone help me with fixing this error? 谁能帮助我解决此错误?

If you have more than one .c file and include your header into them then each one of them will have that file defined inside (as the preprocessor just takes your header code and stuffs it into it before compilation). 如果您有多个.c文件并将头文件包含在其中,则每个文件都将在其中定义该文件(因为预处理器只将您的头文件代码填充到文件中,然后再进行编译)。 If you then compile them together (as in a library) you will get that particular linker error. 如果随后将它们一起编译(如在库中),则会得到该特定的链接器错误。

The solution is to move these definitions: FILE *file=NULL; static FILE *outLog=NULL; pthread_t producer;//Producer Thread ID pthread_t consumer[MAX_PROCS];//consumer thread ID 解决方案是移动这些定义: FILE *file=NULL; static FILE *outLog=NULL; pthread_t producer;//Producer Thread ID pthread_t consumer[MAX_PROCS];//consumer thread ID FILE *file=NULL; static FILE *outLog=NULL; pthread_t producer;//Producer Thread ID pthread_t consumer[MAX_PROCS];//consumer thread ID

into just one of your .c files. 到您的.c文件之一。 Eventually you could leave them into the header marked with the extern keyword to let the linker know they're defined elsewhere. 最终,您可以将它们留在标有extern关键字的标头中,以使链接程序知道它们是在其他位置定义的。 Having definitions inside header files is usually not such a good practice. 在头文件中包含定义通常不是一个好习惯。 The header files should also be guarded against multiple inclusions conflicts as in: 头文件还应防止出现多个包含冲突,如下所示:

#ifndef MY_HEADER_H__
#define MY_HEADER_H__

... your code here

#endif

Another solution would be to make all of them static into your header. 另一个解决方案是将所有这些静态化到您的标头中。 However this would mean that each .c file will access its own data. 但这意味着每个.c文件将访问其自己的数据。

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

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