Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 518 Vote(s) - 3.44 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I use extern to share variables between source files?

#1
I know that global variables in C sometimes have the `extern` keyword. What is an `extern` variable? What is the declaration like? What is its scope?

This is related to sharing variables across source files, but how does that work precisely? Where do I use `extern`?
Reply

#2
Adding an `extern` turns a variable _definition_ into a variable _declaration_. See [this thread](

[To see links please register here]

) as to what's the difference between a declaration and a definition.
Reply

#3
extern tells the compiler to trust you that the memory for this variable is declared elsewhere, so it doesnt try to allocate/check memory.

Therefore, you can compile a file that has reference to an extern, but you can not link if that memory is not declared somewhere.

Useful for global variables and libraries, but dangerous because the linker does not type check.


Reply

#4
Extern is the keyword you use to declare that the variable itself resides in another translation unit.

So you can decide to use a variable in a translation unit and then access it from another one, then in the second one you declare it as extern and the symbol will be resolved by the linker.

If you don't declare it as extern you'll get 2 variables named the same but not related at all, and an error of multiple definitions of the variable.
Reply

#5
I like to think of an extern variable as a promise that you make to the compiler.

When encountering an extern, the compiler can only find out its type, not where it "lives", so it can't resolve the reference.

You are telling it, "Trust me. At link time this reference will be resolvable."
Reply

#6
The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through