unix系统编程中一个关于宏的问题?

编写一个程序实现who命令的效果有如下代码:

#include <stdio.h>
#include <stdlib.h>
#include <utmpx.h>
#include <time.h>

#define SHOWHOST

void show_info(struct utmpx *);
void showtime(long);

int main()
{
    struct utmpx *current_record;

    while((current_record = getutxent()) != NULL)
    {
        show_info(current_record);
    }
    return 0;
}

void show_info(struct utmpx *utbufp)
{
    if(utbufp->ut_type != USER_PROCESS)
        return;
    printf("%-8.8s", utbufp->ut_user);
    printf(" ");
    printf("%-8.8s", utbufp->ut_line);
    printf(" ");
    showtime(utbufp->ut_xtime);
    printf(" ");
    #ifdef SHOWHOST
    if(utbufp->ut_host[0] != '\0')
        printf("(%s)", utbufp->ut_host);
    #endif
    printf("\n");
}

void showtime(long sectime)
{
    char *cp;
    cp = ctime(&sectime);
    printf("%12.12s", cp+4);
}

gcc编译的时候出现了下面的错误

deweixudeMBP:ulix deweixu$ gcc who.c -o who.out 
who.c:30:22: error: no member named 'ut_xtime' in 'struct utmpx'
    showtime(utbufp->ut_xtime);

1 error generated.


在`utmpx.h`中定义了宏`ut_xtime`,为什么会这样?
#ifdef _UTMPX_COMPAT
#define ut_user ut_name
#define ut_xtime ut_tv.tv_sec
#endif /* _UTMPX_COMPAT */

struct utmpx {

char ut_user[_UTX_USERSIZE];    /* login name */
char ut_id[_UTX_IDSIZE];    /* id */
char ut_line[_UTX_LINESIZE];    /* tty name */
pid_t ut_pid;            /* process id creating the entry */
short ut_type;            /* type of this entry */
struct timeval ut_tv;        /* time entry was created */
char ut_host[_UTX_HOSTSIZE];    /* host name */
__uint32_t ut_pad[16];        /* reserved for future use */

};

阅读 2.8k
2 个回答

你编译的时候没有指定
-DHAVE_UTMPX -D_UTMPX_COMPAT
之类的宏,所以ifdef没有满足。不过为了不改变逻辑,你最好还是别指定这些宏,而是直接用ut_tv.tv_sec

    #ifdef _UTMPX_COMPAT
    #define ut_user ut_name
    #define ut_xtime ut_tv.tv_sec
    #endif /* _UTMPX_COMPAT */

ifdef指令,所以里面的宏ut_user, ut_xtime都是未定义,所以后面也没有替换

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进