手动编译apue中的代码但得到错误

时间:2015-07-09 04:09:54

标签: linux compilation

我自己输入了apue的附录B的代码。但是当我做第一次测试时,我得到一个错误。

`(master)⚡ [1] % clang -o myls myls.c apue.c`                               `~/Code/c/apue`
/tmp/apue-cf5ea0.o: In function `log_open':

apue.c:(.text+0xb95): undefined reference to `log_to_stderr'

/tmp/apue-cf5ea0.o: In function `log_doit':

apue.c:(.text+0xe28): undefined reference to `log_to_stderr'

x86_64-pc-linux-gnu-clang-3.5.0: error: linker command failed with exit code 1 (use -v to see invocation)

这是我的apue.c的一部分:

#include <errno.h>
#include <stdarg.h>
#include <syslog.h>
#include "apue.h"

static void log_doit(int, int, int, const char *, va_list ap);

extern int log_to_stderr;

void log_open(const char *ident, int option, int facility) {
  if (log_to_stderr == 0)
    openlog(ident, option, facility);
}
static void log_doit(int errnoflag, int error, int priority, const char *fmt,
                     va_list ap) {
  char buf[MAXLINE];

  vsnprintf(buf, MAXLINE-1, fmt, ap);
  if (errnoflag)
    snprintf(buf+strlen(buf), MAXLINE-strlen(buf)-1, ": %s",
             strerror(error));
  strcat(buf, "\n");
  if (log_to_stderr) {
    fflush(stdout);
    fputs(buf, stderr);
    fflush(stderr);
  } else {
    syslog(priority, "%s", buf);
  }
}

我输入了extern int log_to_stderr,但为什么我也会收到错误? 我使用linux-gentoo。

1 个答案:

答案 0 :(得分:0)

如果使用extern声明一个元素而不定义它(如果一个变量在没有初始化的情况下声明一个变量),则不会分配声明元素的内存,这会导致编译错误

确保您已在log_to_stderr中声明myls.c

int log_to_stderr;