C语言extern关键字定义外部变量--Redis源码extern使用

本文探讨了在Redis 2.8的networking.c文件中,如何利用extern关键字引用全局变量。在没有对应的networking.h头文件情况下,通过引入redis.h并使用extern声明server结构体变量,确保了编译的正确性。同时,文章引用了多本C语言教程对extern和头文件的原理进行了简要说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Redis2.8中有networking.c,这个文件没有networking.h

networking.c首先引入redis.h这个头文件

#include "redis.h"


在redis.c一开始就声明了全局变量

/* Global vars */
struct redisServer server;

networking.c的createClient函数

redisClient *createClient(int fd) {
    redisClient *c = zmalloc(sizeof(redisClient));

    /* passing -1 as fd it is possible to create a non connected client.
     * This is useful since all the Redis commands needs to be executed
     * in the context of a client. When commands are executed in other
     * contexts (for instance a Lua script) we need a non connected client. */
    if (fd != -1) {
        anetNonBlock(NULL,fd);
        anetEnableTcpNoDelay(NULL,fd);
        if (server.tcpkeepalive)
            anetKeepAlive(NULL,fd,server.tcpkeepalive);
        if (aeCreateFileEvent(server.el,fd,AE_READABLE,
            readQueryFromClient, c) == AE_ERR)
        {
            close(fd);
            zfree(c);
            return NULL;
        }
    }

这里之所以可以引用redisClient就是因为redisClient在redis.h是被声明为 extern的,而networking.c已经引入redis.h这个头文件

/*-----------------------------------------------------------------------------
 * Extern declarations
 *----------------------------------------------------------------------------*/

extern struct redisServer server;


不然注释掉extern struct redisServer server是编译不过去的:


关于extern和头文件的解释:


出自《C语言入门经典(第四版)》



出自《21天学通C语言(第6版)》


出自《C语言编程:一本全面的C语言入门教程 (第3版)》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值