链接器为什么看不到我的函数(定义宏来替换syslog)?

时间:2017-02-24 10:37:11

标签: c++ c macros include 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.c pp 文件的列表。 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.

1 个答案:

答案 0 :(得分:0)

“外部”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>

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