Why does the C++ linker allow undefined functions?

后端 未结 3 810
谎友^
谎友^ 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:27

    X doesn't need to be "bound" to a function, because you stated in your code that such function exists. So compiler can safely assume, that the address of this function must not be NULL. For that to be possible, you'd have to declare the function to be a weak symbol, and you didn't. Linker did not protest, because you never call your function (you never use its actual address), so it sees no problem.

提交回复
热议问题