简体   繁体   中英

Xcode C++ extern variable linker error

I am learning to code in C++ and am working in Xcode9.1 on OS X 10.13.1. While trying to understand the use of keyword extern, I encountered the problem that the following code:

extern int foo;
#include <iostream>

int main() {
    foo = 7;
    std::cout << foo << std::endl;
    return 0;
}

results in a linker error when run:

Undefined symbols for architecture x86_64:
  "_foo", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I am not sure why the linker cannot find foo despite the definition being the first line in main .

Thanks very much for looking into my problem!

The linker cannot find foo , because it's not defined anywhere. By declaring extern int foo ', you're telling the linker that the definition is somewhere else. Remove extern , or define foo somewhere where the linker can find it.

Have a look at this example on Wikipedia .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM