Why does the C++ linker allow undefined functions?

后端 未结 3 777
谎友^
谎友^ 2021-02-01 04:03

This C++ code, perhaps surprisingly, prints out 1.

#include 

std::string x();

int main() {

    std::cout << \"x: \" <&l         


        
3条回答
  •  别那么骄傲
    2021-02-01 04:25

    [basic.def.odr]/2:

    A function whose name appears as a potentially-evaluated expression is odr-used if it is the unique lookup result or the selected member of a set of overloaded functions (3.4, 13.3, 13.4), unless it is a pure virtual function and its name is not explicitly qualified.

    Hence, strictly speaking, the code odr-uses the function and therefore requires a definition.
    But modern compilers will realize that the functions exact address is not actually relevant for the behavior of the program, and will thus elide the use and not require a definition.

    Also note what [basic.def.odr]/3 specifies:

    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 implementation is not obliged to halt compilation and issue an error message (=diagnostic). It can do what it considers best. In other words, any action is allowed and we have UB.

提交回复
热议问题