一个C语言函数声明和定义的编译问题

最近在看Redis代码,看到SDS字符串时,有个地方很诡异,代码如下:

static inline size_t sdslen(const sds s) {
    struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
    return sh->len;
}

static inline size_t sdsavail(const sds s) {
    struct sdshdr *sh = (void*)(s-(sizeof(struct sdshdr)));
    return sh->free;
}

sds sdsnewlen(const void *init, size_t initlen);
sds sdsnew(const char *init);
sds sdsempty(void);
<span style="color:#ff0000;">size_t sdslen(const sds s);</span>
sds sdsdup(const sds s);
void sdsfree(sds s);
size_t sdsavail(const sds s);
sds sdsgrowzero(sds s, size_t len);
sds sdscatlen(sds s, const void *t, size_t len);
sds sdscat(sds s, const char *t);
sds sdscatsds(sds s, const sds t);
sds sdscpylen(sds s, const char *t, size_t len);
sds sdscpy(sds s, const char *t);
先是定义了一个内联函数,然后又声明了一个同名的函数,这样不会有问题吗?

根据验证,说明后面的声明是无效的,sds.c文件中没有sdslen的实现,如果有就会重定义错误。用的时候都是调用的内联函数。

测试代码如下:

test.h文件

#include <stdio.h>

static inline void testA()
{
	printf("static inline testA!\n");
}

void testA(); // 不能实现,否则重定义,可以声明,无用
void testB(); // 可以不实现,不实现则不能调用,否则链接不到

test.c文件

#include "test.h"

// void testA()
// {
// }


main函数:

#include "test.h"

void main()
{
	testA(); // inline 函数展开
	// testB(); 不能调用
}

估计是源代码优化未删除原有声明导致的吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值