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

我有多个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" 

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 

两者都失败了。

 $ 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...... 

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

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

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

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

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

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