Reputation: 109
I have a problem with Duplicate Definition error. I have to write a constant inside an header file which is called by other files, but that error occurs and I don't know how to resolve it. I try to use an include guard, but it doesn't work.
#ifndef _DEFINE_PORTS__H___INCLUDED
#define _DEFINE_PORTS__H___INCLUDED
#define GPIO_SWPWM_PORT GPIOB
const uint16_t GPIO_SWPVM_LEDS[12] = {GPIO_Pin_0 , GPIO_Pin_1 , GPIO_Pin_2 ,
GPIO_Pin_3 , GPIO_Pin_4 , GPIO_Pin_5 ,
GPIO_Pin_6 , GPIO_Pin_7 , GPIO_Pin_8 ,
GPIO_Pin_10 , GPIO_Pin_12 , GPIO_Pin_14};
#endif // _DEFINE_PORTS__H___INCLUDED
Following the error (there are more like this);
Error[Li006]: duplicate definitions for "GPIO_SWPVM_LEDS"; in "C:\Andrea\Dev\stm32\ew\Debug\Obj\App.o", and "C:\Andrea\Dev\stm32\ew\Debug\Obj\AppEeprom.o"
Upvotes: 1
Views: 1555
Reputation: 50775
Header guards won't help here, they address only the problem of including the header file more than once in the same compilation unit (AKA .c file).
Here you define a non static variable in a header file. If you do this, all .c files that include this header file will compile cleanly, but during the linking process all these variables will be multiply defined. It's just like if you'd put a function definition into a header file.
You should either have this in your header file:
static const uint16_t GPIO_SWPVM_LEDS[12] = {......};
...or have this in the header file (which is much is much cleaner, because the const variable will exist only once):
extern const int GPIO_SWPVM_LEDS[12];
and put the variable definiton in one of your .c files:
const uint16_t GPIO_SWPVM_LEDS[12] = {......};
Read this SO article for more information:
Upvotes: 3