main.c中定义的宏在另一个包含的文件中不可见

Mig*_*ork 3 c macros gcc avr-gcc

我有多个C和H文件

main.c我定义一个宏,并在ws_driver.c我想使用它.

ws_driver.h包括在内main.c.

main.c中

#define WS_PORT PORT_D8
#define WS_BIT D8
#define WS_DDR DDR_D8

#include "ws_driver.h"
Run Code Online (Sandbox Code Playgroud)

ws_dirver.c我有两个检查:

ws_driver.c

#include "ws_driver.h"

#ifndef WS_PORT
# error "WS_PORT not defined!"
#endif

#ifndef WS_BIT
# error "WS_BIT not defined!"
#endif
Run Code Online (Sandbox Code Playgroud)

两者都失败了.

$ avr-gcc -std=gnu99 -mmcu=atmega328p -DF_CPU=16000000UL -Os -I. -I -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums -Wall -Wstrict-prototypes -Wno-main -Wno-strict-prototypes -Wno-comment -g2 -ggdb -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--relax -std=gnu99 main.c  ws_driver.c --output main.elf
ws_driver.c:10:3: error: #error "WS_PORT not defined!"
 # error "WS_PORT not defined!"
   ^
ws_driver.c:14:3: error: #error "WS_BIT not defined!"
 # error "WS_BIT not defined!"
   ^
ws_driver.c: In function 'ws_show':
ws_driver.c:23:20: error: 'WS_PORT' undeclared (first use in this function)
 #define bus_low() (WS_PORT) &= ~(1 << WS_BIT)
                    ^
ws_driver.c:37:2: note: in expansion of macro 'bus_low'
  bus_low();
  ^
ws_driver.c:23:20: note: each undeclared identifier is reported only once for each function it appears in
 #define b......
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?请询问您是否要查看代码的其他部分.

Don*_*hev 8

如果要在多个位置使用它们,则必须在头文件中定义宏,而不是在.c文件中定义宏.

当编译器编译ws_driver.c它时只包含ws_driver.h并且宏不存在.它不包括main.c. 每个.c文件都是单独编译的.

在说明中移动宏定义config.h并将其包含在您需要的任何位置.

您也可以使用编译器的define -DWS_BIT=123 -DOTHER=SMTH.您传递的值将在生成的目标文件中,如果不重新编译则无法更改.

如果只想编译一次,那么将它们作为参数传递或创建一个 configure_my_library()函数......

  • “您必须在头文件中定义宏,而不是在 .c 文件中” - 谢谢! (4认同)