最近在开发一款STM32F0的单片机的项目,在写程序的时候发现了一些关于重复定义的想法和问题。
我在头文件将数据变量进行了定义
#ifndef _usart_h
#define _usart_h
#include "sys.h"
#define MAX_RX_LENGTH 50
u8 USART1_RX_BUF[MAX_RX_LENGTH]; //串口1的接收缓冲区-缓冲区50个字节
u8 USART1_RX_STA; //串口1接收状态位
u8 USART1_RX_COUNT; //串口1接收的数据长度
#endif
我在主函数进行头文件的调用,编译完成后报错,
.\Objects\template.axf: Error: L6200E: Symbol USART1_RX_BUF multiply defined (by usart.o and main.o).
.\Objects\template.axf: Error: L6200E: Symbol USART1_RX_STA multiply defined (by usart.o and main.o).
.\Objects\template.axf: Error: L6200E: Symbol USART1_RX_COUNT multiply defined (by usart.o and main.o).
我们发现编译器报了一个关于重复定义的错误,但是我们并没有进行重复定义,最后发现,MDK是不能在头文件里面定义变量。
因为头文件在所有工程里,通常都不会被调用一次,编译器会多次调用头文件,他就会误判你重复定义了。
正确的方法是在.c文件里面定义,然后再头文件里面用extern引用就可以啦。
#include "usart.h"
u8 USART1_RX_BUF[MAX_RX_LENGTH]; //串口1的接收缓冲区-缓冲区50个字节
u8 USART1_RX_STA =0; //串口1接收状态位
u8 USART1_RX_COUNT =0; //串口1接收的数据长度
#ifndef _usart_h
#define _usart_h
#include "sys.h"
#define MAX_RX_LENGTH 50
extern u8 USART1_RX_BUF[MAX_RX_LENGTH]; //串口1的接收缓冲区-缓冲区50个字节
extern u8 USART1_RX_STA; //串口1接收状态位
extern u8 USART1_RX_COUNT; //串口1接收的数据长度
#endif
还有,你会发现很多头文件里面也定义了一些变量,这些变量是结构体成员的函数,但是他们并没有报错,因为结构体变量并没有再头文件进行定义,而只是声明结构体变量,是没有分配空间的,这样重复编译就不会出现问题。
声明结构体
以GPIO为例
/**
* @}
*/
/**
* @brief GPIO Init structure definition
*/
typedef struct
{
uint32_t GPIO_Pin; /*!< Specifies the GPIO pins to be configured.
This parameter can be any value of @ref GPIO_pins_define */
GPIOMode_TypeDef GPIO_Mode; /*!< Specifies the operating mode for the selected pins.
This parameter can be a value of @ref GPIOMode_TypeDef */
GPIOSpeed_TypeDef GPIO_Speed; /*!< Specifies the speed for the selected pins.
This parameter can be a value of @ref GPIOSpeed_TypeDef */
GPIOOType_TypeDef GPIO_OType; /*!< Specifies the operating output type for the selected pins.
This parameter can be a value of @ref GPIOOType_TypeDef */
GPIOPuPd_TypeDef GPIO_PuPd; /*!< Specifies the operating Pull-up/Pull down for the selected pins.
This parameter can be a value of @ref GPIOPuPd_TypeDef */
}GPIO_InitTypeDef;
定义结构体变量
GPIO_InitTypeDef GPIO_InitStructure;
路漫漫其修远兮,吾将上下而求索。本人能力有限,若有错误,希望指正,共同进步。