为什么链接器看不到我的函数(定义宏来替代系统日志)?

Why the linker does not see my function (define macro to substitute the syslog)?

我尝试以这种方式替换 syslog 函数:

#include <cstdio>
#include <cstdarg>

void syslog_printf(int level, char* format, ...)
{
  va_list params;
  va_start(params, format);
  vprintf(format, params);
  printf("\n");
  va_end(params);
}

#define syslog(...) syslog_printf(__VA_ARGS__)

#include <modbus/modbus.c>

这是我的 modbus.cpp 文件的列表。 modbus.c 也在那里,但我不能修改它,因为它在几个地方使用。 modbus.cpp 编译正确,但链接器报告找不到 syslog_printf 函数。

问题很简单:为什么?

编辑:

make -k all 
Building file: ../modbus.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -DDEBUG -I../../include -O0 -g3 -Wall  -c -fmessage-length=0 -MMD -MP -MF"modbus.d" -MT"modbus.d" -o "modbus.o" "../modbus.cpp"
Finished building: ../modbus.cpp

Building target: fire
Invoking: GCC C++ Linker
g++  -o "fire"  ./main.o ./modbus.o  
./modbus.o: In function `error_treat(modbus_param_t*, int, char const*)':
../../include/modbus/modbus.c:144: undefined reference to `syslog_printf'
./modbus.o: In function `modbus_send(modbus_param_t*, unsigned char*, int)':
../../include/modbus/modbus.c:379: undefined reference to `syslog_printf'
./modbus.o: In function `receive_msg(modbus_param_t*, int, unsigned char*, int*)':
../../include/modbus/modbus.c:482: undefined reference to `syslog_printf'
../../include/modbus/modbus.c:484: undefined reference to `syslog_printf'
../../include/modbus/modbus.c:511: undefined reference to `syslog_printf'
./modbus.o:../../include/modbus/modbus.c:524: more undefined references to `syslog_printf' follow
collect2: error: ld returned 1 exit status
make: *** [makefile:46: fire] Error 1
make: Target 'all' not remade because of errors.

编辑:

如果我尝试将 modbus.cpp 切换为 modbus.c,我会得到:

make -k all 
Building file: ../modbus.c
Invoking: GCC C Compiler
gcc -DDEBUG -I../../include -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"modbus.d" -MT"modbus.d" -o "modbus.o" "../modbus.c"
../modbus.c:13:21: error: conflicting types for ‘syslog_printf’
 #define syslog(...) syslog_printf(__VA_ARGS__)
                     ^
../modbus.c:4:6: note: previous definition of ‘syslog_printf’ was here
 void syslog_printf(int level, char* format, ...)
      ^~~~~~~~~~~~~
make: *** [subdir.mk:34: modbus.o] Error 1
make: Target 'all' not remade because of errors.

"outer" modbus.c 的正确变体是

#include <stdio.h>
#include <stdarg.h>
#include <syslog.h> // I could include it earlier than the "inner" modbus.c will do...

void syslog_printf(int level, char* format, ...)
{
  va_list params;
  va_start(params, format);
  vprintf(format, params);
  printf("\n");
  va_end(params);
}

#define syslog(...) syslog_printf(__VA_ARGS__)

#include <modbus/modbus.c>

谢谢大家,评论了我的问题。