- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
测试.cpp
#include <iostream>
void f()
{
std::cout<<"non-inline"<<std::endl;
}
主要.cpp
#include <iostream>
using namespace std;
inline void f()
{
cout<<"inline"<<endl;
}
int main()
{
f();
return 0;
}
在 Debug模式下,输出为:非内联。命令:g++ [-g] -o main main.cpp test.cpp
在 Release模式下,输出是:inline。命令:g++ -O -o main main.cpp test.cpp
为什么?
Linux G++ 4.7.3
在C99中,内联定义不提供函数的外部定义,所以我们可以通过在其他源文件中定义另一个函数来提供标识符的外部定义。
内联定义是否为 C++ 中的函数提供外部定义??
谢谢!!
最佳答案
您的程序具有 UB(未定义行为),因为它通过提供 f()
的两种不同定义违反了 ODR(单一定义规则)。因此几乎没有办法推理为什么它会以这种或那种方式表现。在 UB 的最佳传统中,任何行为都是可能的(包括通过 Internet 订购比萨饼)。
编辑
标准 (ISO/IEC 14882:2011) 中的这些引用证明它是 UB:
[basic.def.odr]§3:
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. ... An inline function shall be defined in every translation unit in which it is odr-used.
[basic.def.odr]§5:
There can be more than one definition of ... inline function with external linkage ... in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then
- each definition of D shall consist of the same sequence of tokens; and
- ...
[dcl.fct.spec]§4
An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its definition appears in the translation unit. -end note ] If the definition of a function appears in a translation unit before its first declaration as inline, the program is ill-formed. If a function with external linkage is declared inline in one translation unit, it shall be declared inline in all translation units in which it appears; no diagnostic is required. ...
(强调我的)
关于c++ - 当存在与内联函数同名的外部函数时调用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18629184/
我有 json 数据: { "products": [ { "productId" : 0, "productImg" : "../img/product-ph
我是一名优秀的程序员,十分优秀!