Why wouldn't this code work? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I dont understand why this wouldn't work. Thanks!
#include<stdio.h>
#include<conio.h>
int main()
{
extern int i;
int i=20;
printf("%d",i);
}
Compilation results in the following error:
main.c: In function 'main':
main.c:6:9: error: declaration of 'i' with no linkage follows extern declaration
main.c:5:16: note: previous declaration of 'i' was here
Note: Code compiled online at CompileOnline

This won't work since you're trying to use i in two very different ways in the same scope.
The name i can't refer to both some extern data that someone else is defining, and a local variable.
If you just want to assign to the external variable, don't re-declare it:
extern int i;
i = 20;

You've already declared i as an int in
extern int i;
And then you go ahead and declare it again with
int i=20;
Try doing this instead
extern int i;
i=20;

You are mistakenly re declaring i
#include <stdio.h>
#include <conio.h>
int main()
{
extern int i;
i=20; //Simply assign the value here. why redeclare with `int`
printf("%d",i);
}

int i;
Here variable i is declared and memory is allocated for it but not initialized.
extern int i;
Whenever extern is used, the variable is just declared and memory will not be allocated for it. In order to access it you have to redeclare same variable externally.
Here extern refers to that, you will be defining the value of that variable(i) outside the program(external source). In your case, you do it inside so it will not work as you expected. It can be either defined outside main program or by external programs.
Try this:
#include<stdio.h>
int main()
{
extern int i; //Declared but memory not allocated
printf("%d",i);
return 0;
}
int i=20; //Allocated memory for i and initialized to 20 outside the prog
Output:
20
Global extern variables can also be initialized directly, where as local extern variables cannot be.
#include<stdio.h>
extern int i=10; //Declared, Memory allocated and defined.
int main()
{
extern int j; //Declared but memory not allocated
printf("%d --> %d",i,j);
return 0;
}
int j=20; //Memory Allocated and value defined externally.
Output:
10 --> 20
You can also refer to this link to know more about it.

you have declared i twice which resulted in redefinition error

extern indicates to the compiler that somewhere outside there exists a variable called i which is of type int.
Here, outside could be in the same program or in some other translation(another .c file) unit.
But you're redeclaring the same i which you already declared.
Also, if you're only executing the following program(without linking other files .c) it wont work:
#include <stdio.h>
#include <conio.h>
int main()
{
extern int i;
i=20;
printf("%d",i);
}
It gives a linker error complaining that i is unresolved because the linker was unable to find the definition for i and no storage was allocated to it as it is not defined outside the main.

Related

Global value is not acessable in another file? [duplicate]

This question already has answers here:
How do I use extern to share variables between source files?
(19 answers)
Closed 8 years ago.
Global value is not accessible in another file?Mycode is below please help me to fix
flie1.c
#include<stdio.h>
extern int i=9;
int main()
{
printf("i m in main\n");
}
file2.c
printf("%d\n",i);
i am compiling both file at once as cc file1.c file2.c
Change it like this, and it will work:
file1.c
#include <stdio.h>
int i = 9; // define the variable
void print(); // declare print: say there is a function called `print` with no arguments and no return type (because the function is DEFINED in file2.c)
int main() {
printf("im in main");
print();
return 0;
}
file2.c
extern int i; // declare "i": say there is a variable called `i` with type of `int` (because the variable is DEFINED in file1.c)
void print() {
printf("%d\n", i);
}
When you have an extern variable, it should also have its 'original' declaration (without using extern). extern simply says ' this variable is defined elsewhere', so you need to define the variable somewhere.
Simply add:
int i=9;
to file2.c (in the top of the file, the 'globals' area')
and you can change your extern declaration to:
extern int i;
(without the assignment of the value 9) in file1.c

what is the difference between the two codes?

this is the first code
#include <stdio.h>
void a();
int i;
int main()
{
printf("%d\n",i);
a();
return 0;
}
int i=5;
void a()
{
printf("%d\n",i);
}
output
5
5
the second code is
#include <stdio.h>
void a();
extern int i;
int main()
{
printf("%d\n",i);
a();
return 0;
}
int i=5;
void a()
{
printf("%d\n",i);
}
ouput
5
5
what is the difference between the codes if their outputs are same...
and if they are same then what is the use of extern
extern is something like saying to the Linker that you have defined the variable in some other file( even global variables can be made extern inside other functions in same file) don't throw error now you will find the variable later then link it .
using extern your only declaring the variable not defining it(no memory allocated).
In Your second program for first declartion
extern int i;
No memory is allocated but later when you declare
int i = 5 ;
the memory is allocated for i. while linker searches for i in printf if i is not declared extern it throws a error since its extern linking takes place when it finds the defintion of i.
extern means that you are declaring the variable but not defining it (allocating memory for it). Have a look at this link for a good explanation of extern: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

Accessing the global variable when global and local variables have same name

I have some doubt on below code
#include<stdio.h>
int i=6;
int main()
{
int i=4;
{
extern int i;
printf("%d",i); //prints 6
}
printf("%d",i); //prints 4
}
we know that extern keyword says compiler, the variable is somewhere outside. So the question is why the extern keyword is accessing the global i variable but not the i variable which is within the main function? I was thinking there must be a contradiction because both variables are available to the inner braces as global variable. So does extern keyword access the variable which is outside the function or does it also access the variable which is outside the braces.
extern doesn't mean outside the current scope, it means an object with external linkage. An automatic variable never has external linkage, so your declaration extern int i can't possibly refer to that. Hence it's hiding it, the same as the automatic variable hid the global.
Before the printf that prints 6 you are asking the compiler to use the i defined after the #include. The closing brace then tells the compiler that the extern is no longer in effect, therefore it uses the scope where i is set to 4.
int i=4 is not global variable, if you try to access var i which is inside main in another function your compiler will thrown error about var i is undeclared. This code illustrates it.
void func() {
printf("i is %d\n",i);
}
main() {
int i=10;
func();
}
Whereas the i outside of main is global variable, which you can access in all functions.
I think you're asking whether you're right in thinking that the extern int i declaration should cause the first printf to resolve i to 4 because that int i=4 statement is in a parent scope of the scope in which the extern is declared.
The answer is no, hence the behaviour you're seeing. An extern declaration within a function is used to declare the existence of an external variable and won't ever resolve to a local variable (a variable declared within the function).
/* what Ed Heal said */
Yet, I think it would be best to illustrate it with additional example. I modified Your example to do a little more. The comments in the code tells the most of it:
#include <stdio.h>
int i = 6;
int main(void)
{
int i = 4;
printf("%d\n", i); /* prints 4 */
{
extern int i; /* this i is now "current". */
printf("%d\n", i); /* prints 6 */
{
int *x = &i; /* Save the address of the "old" i,
* before making a new one. */
int i = 32; /* one more i. Becomes the "current" i.*/
printf("%d\n", i); /* prints 32 */
printf("%d\n", *x); /* prints 6 - "old" i through a pointer.*/
}
/* The "previous" i goes out of scope.
* That extern one is "current" again. */
printf("%d\n", i); /* prints 6 again */
}
/* That extern i goes out of scope.
* The only remaining i is now "current". */
printf("%d\n", i); /* prints 4 again */
return 0;
}

Extern Variable

int main()
{
extern int i;
i=20;
printf("%d",i);
return 0;
}
The compiler is giving an Error that 'i' is undefined
Whats the Reason?
Difference :
1.int i; // i is defined to be an integer type in the current function/file
2.extern int i; // i is defined in some other file and only a proto-type is present here.
Hence while compiling, the compiler(LDD) will look for the original definition of the variable and if it does'nt find, it'll throw an error 'undefined reference to `i'.
By saying extern you tell the compiler that i is defined in a different translation unit, which I'm guessing you don't have. There's a difference between declaration and definition in C. In short, the former is telling the compiler the type of the variable, the latter is telling to allocate storage for it.
Just drop that extern for now.
i has no storage location.
You must link with a translation unit that includes int i; (not extern).
extern
Allows one module of your program to access a global variable or function declared in another module of your program.
You usually have extern variables declared in header files.
If you don't want a program to access your variables or functions, you use static which tells the compiler that this variable or function cannot be used outside of this module.
errno.h
#ifndef ERRORS /* prevent multiple inclusion */
#define ERRORS 0
extern int errno; <- Declaring the variable to be external.
extern void seterrorcode(int errcode);
#endif
errno.c
#include "errno.h"
int errno; <- This is where the definition of errno occurs
static int stuff; <- This is private to this module.
void seterrorcode(int errcode)
{
errno = errcode;
}
main.c
#include "errno.h"
/* extern int stuff : This line will produce an undefined variable error when linking */
int main()
{
seterrorcode(0);
if (errno > 0)
; /* Error code > 0, do something */
}
For more Info
extern keyword is used to tell the compiler that the variable
is defined in another file
but during linking, the linker does not resolve the variable
so you get an error
1.For this question,you need to understand that definition is a superset of declaration.In declaration,we just introduce the variable that is going to be used but do not allocate any memory to it.But in the case of definition,we both declare and allocate memory to the variable.
2.int i;
This sentence will both declare and define the variable i
3.On the other hand
extern int i;
This sentence will just extend the visibility of the variable to the whole program.Effectively,you are just defining the variable and not declaring it.
i=20;
this line is trying to assign 20 to a variable that does not exist.
4.It can be corrected by writing
extern int i=20;
Hope this helps!

extern and global in c

Can anyone please tell me is there any special requirement to use either EXTERN or GLOBAL variables in a C program?
I do not see any difference in a program like below, if I change from gloabl to extern.
#include <stdio.h>
#include <stdlib.h>
int myGlobalvar = 10;
int main(int argc, char *argv[])
{
int myFunc(int);
int i;
i = 12;
myGlobalvar = 100;
printf("Value of myGlobalvar is %d , i = %d\n", myGlobalvar, i);
i = myFunc(10);
printf("Value of passed value : %d\n",i);
printf("again Value of myGlobalvar is %d , i = %d\n", myGlobalvar, i);
system("PAUSE");
return 0;
}
int myFunc(int i)
{
i = 20 + 1000;
//extern int myGlobalvar;
myGlobalvar = 20000;
// printf("Value of passed value : %d",i);
return i;
}
If uncomment extern int myGlobalvar, the value does not change.
Is there any correct difference between both?
Can anyone please correct me?
The keyword extern means "the storage for this variable is allocated elsewhere". It tells the compiler "I'm referencing myGlobalvar here, and you haven't seen it before, but that's OK; the linker will know what you are talking about." In your specific example it's not particularly useful, because the compiler does know about myGlobalvar -- it's defined earlier in the same translation unit (.c or .cc file.) You normally use extern when you want to refer to something that is not in the current translation unit, such as a variable that's defined in a library you will be linking to.
(Of course, normally that library would declare the extern variables for you, in a header file that you should include.)
From Here:
A global variable in C/C++ is a variable which can be accessed from any module in your program.
int myGlobalVariable;
This allocates storage for the data, and tells the compiler that you want to access that storage with the name 'myGlobalVariable'.
But what do you do if you want to access that variable from another module in the program? You can't use the same statement given above, because then you'll have 2 variables named 'myGlobalVariable', and that's not allowed. So, the solution is to let your other modules DECLARE the variable without DEFINING it:
extern int myGlobalVariable;
This tells the compiler "there's a variable defined in another module called myGlobalVariable, of type integer. I want you to accept my attempts to access it, but don't allocate storage for it because another module has already done that".
Since myGlobalvar has been defined before the function myFunc. Its declaration inside the function is redundant.
But if the definition was after the function, we must have the declaration.
int myFunc(int i)
{
i = 20 + 1000;
extern int myGlobalvar; // Declaration must now.
myGlobalvar = 20000;
printf("Value of passed value : %d",i);
return i;
}
int myGlobalvar = 10; // Def after the function.
In short: GLOBAL variables are declared in one file. But they can be accessed in another file only with the EXTERN word before (in this another file). In the same file, no need of EXTERN.
for example:
my_file.cpp
int global_var = 3;
int main(){
}
You can access the global variable in the same file. No need to use EXTERN:
my_file.cpp
int global_var = 3;
int main(){
++global_var;
std::cout << global_var; // Displays '4'
}
Global variable, by definition, can also be accessed by all the other files.
BUT, in this case, you need to access the global variable using EXTERN.
So, with my_file.cpp declaring the global_var, in other_file.cpp if you try this:
other_file.cpp
int main(){
++global_var; // ERROR!!! Compiler is complaining of a 'non-declared' variable
std::cout << global_var;
}
Instead, do:
int main(){
extern int global_var;//Note: 'int global_var' without 'extern' would
// simply create a separate different variable
++global_var; // and '++global_var' wouldn't work since it'll
// complain that the variable was not initiazed.
std::cout << global_var; // WORKING: it shows '4'
}
myGlobalVar as you've defined it is a global variable, visible from all the places in your program. There's no need declaring it extern in the same .c file . That is useful for other .c files to let the compiler know this variable is going to be used.

Resources