saitjr
saitjr

Reputation: 159

define a `extern` var in C language, xcode send a `Undefined symbols for architecture x86_64`

This question is hard to describe, I'll try my best. Ok, here is the detail:

  1. I have a public head file, named header.h;
  2. define a extern int a; in header.h;
  3. create test1.c and include header.h;
  4. use var a in test1.c, but xcode give an error:Undefined symbols for architecture x86_64;

I tried to delete extern, and this question is gone. I searched extern in google, they said that if you don't add extern, xcode will auto add extern.Actually, there is difference between add extern by yourself and add extern by xcode. What's difference between then?

Upvotes: 2

Views: 6104

Answers (1)

Kevin
Kevin

Reputation: 56129

When you declare a variable extern, that's a promise to the compiler, "Trust me, this will be there when you need it." It doesn't make the variable, it just tells the compiler that it's declared for real somewhere, and the compiler doesn't need to know where.

You lied to the compiler. You didn't actually declare the variable anywhere, you just said you would. Then when the linker looked for it, it couldn't find it.

When you took away the extern, that turned the promise of a variable into an actual declaration. The compiler didn't have to believe you, it just made the variable like you told it to. But because it was in a header, if you included that variable in two different code files and compiled them into separate object files, when you tried to link them you would get an error about duplicate symbols. The proper way to use extern is to declare the variable extern in the header file and then declare it for real in the implementation (.c) file.

header.h:

#ifndef HEADER_H
#define HEADER_H

extern int a;

#endif

test1.c

#include "header.h"

int a = 5;

...

Then you can access the same variable a from a different c file.

test2.c

#include "header.h"

int foo() {
    return a;
}

Upvotes: 10

Related Questions