user1628256
user1628256

Reputation: 319

why function didnt need extern, but variable does

Sorry guys I know my english is bad, but i made examples so that my question is more clearer.

a.cpp

#include <iostream>

using namespace std;

void funcfoo(){
    cout << "test only" << endl;
}

int varfoo = 10;



b.cpp

#include <iostream>

using namespace std;

extern void funcfoo();

extern int varfoo;

int main(){

    funcfoo();

    cout << varfoo;

    return 0;
}

Then I compile it like this "cl b.cpp a.cpp"

My question is. How come when I remove the "extern keyword before void funcfoo()" it works fine, but when i remove the extern keyword before int var foo I get an error?

Upvotes: 3

Views: 363

Answers (4)

nikhs
nikhs

Reputation: 63

I know this might be late, but I hope this helps in some way. Check the link below and it ll give an idea of what extern is and how it works.

http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

Thank you

Upvotes: 0

Vimal Buck
Vimal Buck

Reputation: 1

Another way to think about it is that when you do int varfoo memory is allocated to hold the variable so it is both a definition and a declaration, when you do int foo() the function is declared but not defined so in a way the memory is not allocated. For functions the linkage is external by default so removing it doesn't matter but for the variable, if you say extern int varfoo the compiler will not allocate memory for it --it will assume that the variable is defined somewhere else.

Upvotes: 0

The issue is what each one of the lines of code means. int varfoo is a definition of a variable, while void funcfoo() is only a declaration. You can provide multiple declarations of an entity, but only one definition. The syntax to provide a declaration and only a declaration of a variable is by adding the extern keyword: extern int varfoo; is a declaration


3.1 [basic.def]/2 A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function body [...]

Upvotes: 9

MartyE
MartyE

Reputation: 646

When you remove the extern from extern void funcfoo(); you are forward declaring it so you're code below will know what funcfoo() is. If you were to do that to a variable, you would actually be instantiating it and would conflict with your other file. Hence the extern is saying "it exists, trust me ;)" that it gets resolved from your other file.

Upvotes: 3

Related Questions