开发者

Linker error structure header in C

开发者 https://www.devze.com 2023-01-23 19:10 出处:网络
I have structure declaration in a header globalStruct.h #ifndef _GLOBALSTRUCT_H #define _GLOBALSTRUCT_H typedef struct

I have structure declaration in a header globalStruct.h

#ifndef _GLOBALSTRUCT_H
#define _GLOBALSTRUCT_H
typedef struct 
    {
        
        Int32   frameID;
        Int32   slotIndx;
        Int32   symNumber;

    }   recControlList;     
        recControlList  *recControlListPtr;

#endif

fun.h is

include "globalStruct.h"

void 开发者_如何学JAVAfun( recControlList *recControlListPtr);

Inside File1.c I do the following

#include "globalStruct.h"
#include "fun.h"

recControlList  temp;
recControlListPtr=&temp;

fun( recControlListPtr); //Function prototype is declared in some fun.h file.

fun.c looks like

#include "globalStruct.h"

void fun( recControlList *recControlListPtr)

I get linker error: _recControlListPtr defined multiple times. one in File1.c and other fun.c

I don't understand what is wrong here? globalStruct needs extern?

Thanks


Include guards won't help you here. They will stop a single compilation unit from getting two copies of the data if it includes the header file twice but you have two totally separate compilation units here. The compiler will put a recControlListPtr in both of the object files.

Then, when you link those object files together, the linker will complain because there are two instances of that symbol.

What you need to do is ensure that only one instance exists. In your header file, replace:

recControlList  *recControlListPtr;

with:

extern recControlList  *recControlListPtr;

Then, in one of your C files, put:

recControlList  *recControlListPtr;

Bottom line: try to avoid defining anything in header files. Declaring things (stating that they exist, like prototypes, externs, typedefs, structs and so on) is okay, defining (allocating space for variables, giving the bodies of functions ans so on) is generally not.


If you include a header file more than once throughout your program you have to either:

a) be more careful with the declarations you have in the header

OR

b) put include guards to make sure that the header doesn't get included twice, read up on include guards IFNDEF and IFDEF for more info.

PM

0

精彩评论

暂无评论...
验证码 换一张
取 消