Linker complains about duplicate definition.

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 
已解决

Linker complains about duplicate definition.

跳至解决方案
6,763 次查看
onnimikki
Contributor I

Hi,

I'm having trouble with a global variable being defined in a header file and hen being called from two different .C files. The linker is not happy.  I had Codewarrior autogenerate the MCUinit.c file and have use a global variable in one of the interrupt service routines in MCUinit.c.  I'd like to use this global variable in main.c.  The global is defined in a header I call extras.h, complete with guards:

// extras.h
#ifndef __EXTRAS_H
#define __EXTRAS_H

#define MAX_COUNT 10000
int Count_GLOBAL = 1;

#endif  // __EXTRAS_H

I call #include "extras.h" from both MCUinit.c and main.c but the linker is telling me

Link Error: L1818: Symbol 16 - Count_GLOBAL duplicated in MCUinit.c.o and main.c.o.

When I remove the #include call in either MCUinit.c or main.c the compiler complains that the variable is not declared.

Does anyone know a way around this?  

Thanks!

James

标签 (1)
标记 (1)
0 项奖励
回复
1 解答
5,251 次查看
rocco
Senior Contributor II

Hi James,

 

The header file is there to "declare" functions and variables. Nothing should ever be "defined" in a header file.

 

In order to change "int Count_GLOBAL = 1;" from a definition to a declaration, you need to write it like this:

 

extern int Count_GLOBAL;

 

Of course, this will leave "Count_GLOBAL" declared but undefined, so you need to put your definition in one of your .c files, probably "main.c".

在原帖中查看解决方案

0 项奖励
回复
3 回复数
5,252 次查看
rocco
Senior Contributor II

Hi James,

 

The header file is there to "declare" functions and variables. Nothing should ever be "defined" in a header file.

 

In order to change "int Count_GLOBAL = 1;" from a definition to a declaration, you need to write it like this:

 

extern int Count_GLOBAL;

 

Of course, this will leave "Count_GLOBAL" declared but undefined, so you need to put your definition in one of your .c files, probably "main.c".

0 项奖励
回复
5,251 次查看
Jay24
Contributor I

Hi Rocco,

 

We're developing a product that needs a good algorithm to calculate steps, calories, miles, sleep. Know any company or person(s) you'd recommend for the development or implementation?

 

Thanks

Jay

0 项奖励
回复
5,251 次查看
onnimikki
Contributor I

Super!  Thanks Rocco!

0 项奖励
回复