q0987
q0987

Reputation: 35982

C++ usage extern in front of function

I have seen an interview question from Bloomberg from here: http://www.careercup.com/question?id=383154

extern void print(int *a, int z);
void print(int *a, int z);

Question 1> Will it compile?

Question 2> If it compiles, what does it mean?

extern int i;
int i;

Question 3> Will it compile?

Question 4> If it compiles, what does it mean?

Upvotes: 1

Views: 1155

Answers (4)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145239

Q1 refers to this code:

extern void print(int *a, int z);
void print(int *a, int z);

Whether it will compile depends on where it's placed. For example, at the outermost level within a class definition it will not compile.

struct X
{
    extern void print(int *a, int z);   // invalid storage class for a class member by vs2010
    void print(int *a, int z);
};

int main()
{}

Q2. extern specifies extern linkage, which says the definition can be in another translation unit. This is the default for functions. Your C++ textbook should discuss use of extern and static.

Q3 refers to this code:

extern int i;
int i;

Whether it will compile again depends on the context, where it's placed.

Q4. If it compiles then it's declaring an extern linkage variable i, and defining that variable (it can't be an automatic local variable that's defined because that would be a redefinition of the name i in a way that's not supported by C++).

Cheers & hth.,

Upvotes: 1

Eric Z
Eric Z

Reputation: 14505

// a function declaration
extern void print(int *a, int z);
// still a function declaration
void print(int *a, int z);

Answer 1

Yes, it compiles successfully.

Answer 2

A global function without a body {} is automatically a function declaration. The keyword extern is optional. So both of them are just declarations. And multiple declarations are just fine.

// a variable declaration
extern int i;
// a variable definition without an initializer
int i;

Answer 3

Yes, it compiles successfully.

Answer 4

One is a declaration and the other is definition. Note that this definition doesn't have an initializer though. For global variables, you need explicitly add keyword extern to distinguish a declaration with a definition. And it's perfectly conform to One Definition Rule in C++.

Edit: I cannot open the link there. I assume the code you mentioned is in a global context.

Upvotes: 5

Purnima
Purnima

Reputation: 1022

In the first case it would compile successfully. Here is the link you can refer toIdeone sample test. Since both the cases you are only declaring the functions, it is ok to declare the entities multiple times as long as there is only one definition.

The same rule applies for the second one as well.

Upvotes: 0

Peter Varga
Peter Varga

Reputation: 109

extern in declaration will allocate the memory needed in this compillation unit, and during linking there will be a definition. in a nushell.

Upvotes: 0

Related Questions