为什么没有“未定义的外部变量"?导致C ++ 17中的链接器错误? [英] Why doesn't this "undefined extern variable" result in a linker error in C++17?

查看:95
本文介绍了为什么没有“未定义的外部变量"?导致C ++ 17中的链接器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C ++ 17编译器(Coliru)中编译并运行了以下程序.在程序中,我声明了一个变量,但未定义.但是,编译器不会给出链接器错误.

I have compiled and ran the following program in a C++17 compiler (Coliru). In the program, I declared an extern variable, but did not define it. However, the compiler doesn't give a linker error.

#include <iostream>

extern int i; // Only declaration

int func() 
{
    if constexpr (true)
        return 0;
    else if (i)
        return i;
    else
        return -1;
}

int main() 
{
    int ret = func();
    std::cout<<"Ret : "<<ret<<std::endl;
}

为什么编译器没有给出链接器错误?

推荐答案

因为该变量未被使用.您在那里有一个constexpr if,它总是丢弃可以使用它的分支.

Because the variable isn't odr-used. You have a constexpr if there that always discards the branch that could use it.

constexpr if的要点之一是,被丢弃的分支甚至不需要编译,只需格式正确即可.这样便可以将对不存在的成员函数的调用放置在废弃的分支中.

One of the points of constexpr if is that the discarded branch need not even compile, only be well-formed. That's how we can place calls to non-existing member functions in a discarded branch.

这篇关于为什么没有“未定义的外部变量"?导致C ++ 17中的链接器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆