gpt4 book ai didi

c - 带断言的内联函数会创建 undefined reference ?

转载 作者:行者123 更新时间:2023-11-30 14:48:24 26 4
gpt4 key购买 nike

divide.h

#pragma once

#include <assert.h>

inline int divide(int a, int b)
{
assert(b != 0);
return a / b;
}

main.c

#include <divide.h>

int main(void)
{
divide(10, 2);
return 0;
}

仅仅因为assert,我无法编译以下内容。如果我删除断言,一切都会正常。

$ gcc --version
gcc (GCC) 8.1.0
$ gcc main.c
main.c:(.text+0xf): undefined reference to `divide'
$ gcc main.c -O3 # Compilation with optimization works as asserts are removed.

当放置 divide 的定义时里面 .c文件,一切正常。但是,由于函数声明为 inline ,以下内容不应该也有效吗? ?

最佳答案

C99 标准在 6.7.4“函数说明符”中对内联函数进行了这样的规定:

An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.

因此,实现可以选择不内联函数调用,在这种情况下需要函数的外部定义。我猜想,由于断言是一个调试工具,GCC 不希望内联具有事件断言的函数来帮助调试。

关于c - 带断言的内联函数会创建 undefined reference ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50428869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com