• recategorized by
332 views
11 11 votes

Given the following three files, what will be the output after compiling and linking them together?

file1.c

extern int i;

void f() {
    i++;
}

file2.c

int i = 0;

void f();

void g() {
    f();
}

main.c

#include <stdio.h>

extern int i;

void f();
void g();

int main() {
    f();
    g();

    printf("%d", i);

    return 0;
}
  1. $\texttt{0}$
     
  2. $\texttt{1}$
     
  3. $\texttt{2}$
     
  4. Linker error

3 Answers

2 2 votes

In $\texttt{file2.c}$, the statement $\texttt{int i = 0;}$ is the actual definition of the global variable $\texttt{i}$.

In $\texttt{file1.c}$, the statement $\texttt{extern int i;}$ declares that $\texttt{i}$ is defined somewhere else.

So, $\texttt{file1.c}$ uses the same global $\texttt{i}$ from $\texttt{file2.c}$.

In $\texttt{main.c}$ also, $\texttt{extern int i;}$ refers to the same global variable $\texttt{i}$.

Initially, $\texttt{i = 0}$.

In $\texttt{main()}$, first $\texttt{f()}$ is called.

Function $\texttt{f()}$ does $\texttt{i++}$, so $\texttt{i}$ becomes $\texttt{1}$.

Then $\texttt{g()}$ is called.

Inside $\texttt{g()}$, function $\texttt{f()}$ is called again.

So, $\texttt{i++}$ runs again and $\texttt{i}$ becomes $\texttt{2}$.

Therefore, the output is $\texttt{2}$.

Answer: C

• edited by
0 0 votes
After independent compilaion of the each file, the object files are generated and all the object files are linked to one file and the extern keyword is resolved in all places.
Answer:
Position:
Show:

Related questions

8 8 votes
2 2 answers
257
257 views
GO Classes asked Jun 11
257 views
Given the following two files, what will happen when they are compiled and linked together?file1.c#include <stdio.h static void show() { printf("Hello"); }main.cvoid show...
7 7 votes
2 2 answers
244
244 views
GO Classes asked Jun 11
244 views
What is the output of the following code?#include <stdio.h int x = 10; int main() { int x = 20; { extern int x; printf("%d", x); } return 0; }$\texttt{10}$ $\texttt{20}$ ...
5 5 votes
3 3 answers
245
245 views
GO Classes asked Jun 11
245 views
What is the output of the following code?#include <stdio.h int add(int n) { static int total = 1; total = total + n; return total; } int main() { int i, ans = 0; for (i =...
7 7 votes
2 2 answers
246
246 views
GO Classes asked Jun 11
246 views
What is the output of the following code?#include <stdio.h int x; int x; int main() { printf("%d", x); return 0; }$\texttt{0}$ Garbage value Compilation error Linker erro...