函数err_sys()在哪里定义?

sub*_*ngh 9 c network-programming

我收到与err_sys()此代码相关的错误:

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
    int sockfd;

    if ((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
        err_sys("can't create socket");

    close(sockfd);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我收到链接器错误:

/tmp/cciuUVhz.o: In function `main':
getsockopt.c:(.text+0x38): undefined reference to `err_sys'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

功能在哪里err_sys()定义?

Pat*_*rik 19

将其置于代码之上:

void err_sys(const char* x) 
{ 
    perror(x); 
    exit(1); 
}
Run Code Online (Sandbox Code Playgroud)

perror在stdio.h中定义

err_sys在Richard Stevens的"UNIX网络编程:套接字网络API"一书中使用.据我所知,这并不常见.

编辑:修复代码错误

  • 写的宏有严重的错误,例如`if(foo)err_sys(x); 别的......`失败了.如果你不能写一个正确的宏,使用函数! (5认同)
  • 要把它写成宏,你需要`#define err_sys(x)do {perror(x); 出口(1); } while(0)`.这不会违反`if(foo)err_sys(x); 别的......`问题.它(`do {...} while(0)`)是一种标准技术. (4认同)
  • 为什么不为此使用函数,而不是宏? (2认同)
  • @Patrik:它不会编译. (2认同)

Foo*_*Bah 5

这是来自TCP/IP Illustrated吗?我记得看过这个,并在附录中提供了定义:

#include <errno.h>
#include <stdarg.h>
/*
 * Print a message and return to caller.
 * Caller specifies "errnoflag".
 */
static void
err_doit(int errnoflag, int error, const char *fmt, va_list ap)
{
    char    buf[MAXLINE];
    vsnprintf(buf, MAXLINE, fmt, ap);
    if (errnoflag)
        snprintf(buf+strlen(buf), MAXLINE-strlen(buf), ": %s",
    strerror(error));
    strcat(buf, "\n");
    fflush(stdout);     /* in case stdout and stderr are the same */
    fputs(buf, stderr);
    fflush(NULL);       /* flushes all stdio output streams */
}


/*
 * Fatal error related to a system call.
 * Print a message and terminate.
 */
void
err_sys(const char *fmt, ...)
{
    va_list     ap;
    va_start(ap, fmt);
    err_doit(1, errno, fmt, ap);
    va_end(ap);
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)