Question about static, extern and #pragma once

what is the difference between #pragma once and the static keyword?

aren't they both doing the same; telling the compiler that there's 1 definition of the specific variable, but the header can be included multiple times? why do I have to use static when I'm already using #pragma once?

I don't really understand the extern as I just discovered that, but why do I have to use extern instead of the static when I want to use that one variable in multiple source files? I mean, they both include the header that defines the variable, and the variable is static, so it should be common for both source files and should have the same value, right?

why can't I access the static variable from within a header in second source file? why does it has to be extern? I thought that the static is there for that very reason
#pragma once is used to avoid including a file (normally a header file) multiple times when compiling a source file.
static is used to avoid multiple instances of the same variable: see http://en.cppreference.com/w/cpp/keyword/static.
extern is used to to access a variable defined in another source file: see http://en.cppreference.com/w/cpp/keyword/extern.

why do I have to use static when I'm already using #pragma once?
static is for variables, #pragma once if for file includes.

why do I have to use extern instead of the static when I want to use that one variable in multiple source files
You must use extern in all source file, except for the source file where the variable is defined. That variable could be static or not.

closed account (E0p9LyTq)
static and extern define storage duration and linkage characteristics of objects, #pragma once is a non-standard implementation defined program control.

#pragma once is another way to create a header file inclusion guard.

why can't I access the static variable from within a header in second source file? why does it has [sic] to be extern?

static specifies the linkage to be internal, only visible in the translation unit (.cpp file) it was defined. extern specifies the linkage to be external, defined in one translation unit and visible to any translation unit that has access to the extern declaration (usually in a header file).

The storage duration, static and extern, acts like the object was defined in the global namespace. Created when the program starts, destroyed when the program ends.

Ok, I'll be honest, the above is really simplified, so could be less than 100% accurate. If you can successfully slog your way through what the C++ standard says about #pragma and extern/static, here's a couple of links to read:

http://en.cppreference.com/w/cpp/preprocessor/impl
http://en.cppreference.com/w/cpp/language/storage_duration
Topic archived. No new replies allowed.