在我写树莓派can通信的时候,因为can通信的波特率是1M,就不能使用平常的通信库<termios.h>的termios去初始化串口(例如波特率为9600,115200等等),应该使用<asm/termbits.h>中的termios2去初始化串口,因为<asm/termbits.h>是用来扩展串口配置,例如设置非标准波特率或特殊标志,但是当我们要同时使用这两种通信的时候,同时导入<asm/termbits.h>和<termios.h>,编译过程中会产生重定义struct termios的报错。解决方法如下:
方法一:使用条件编译避免重复包含
可以通过条件编译来避免重复包含导致的冲突。在包含头文件时,使用 #ifndef
和 #define
来确保头文件只被包含一次。示例如下:
#ifndef _TERMIOS_H
#include <termios.h>
#define _TERMIOS_H
#endif
#ifndef _ASM_TERMBITS_H
#include <asm/termbits.h>
#define _ASM_TERMBITS_H
#endif
这样可以确保每个头文件中的内容只被编译一次,减少重定义的可能性。
方法二:重命名结构体(推荐)
如果两个头文件中的 struct termios
定义有差异,且不能修改头文件本身,可以在代码中重命名其中一个结构体。例如,将 <asm/termbits.h>
中的 struct termios
重命名为 struct asm_termios
。可以通过在包含 <asm/termbits.h>
之前使用 #define
来实现:
#include <termios.h>
// 将 asm/termbits.h 中的 struct termios 重命名为 struct asm_termios
#define termios asm_termios
#include <asm/termbits.h>
#undef termios
int main() {
// 使用 <termios.h> 中的 struct termios
struct termios tio;
// 使用 <asm/termbits.h> 中重命名后的 struct asm_termios
struct asm_termios asm_tio;
// 其他代码...
return 0;
}