I got some problem with the following codes particularly in header.c where i can't access the extern int x variable in header.h... Why? Does extern variable in .h not global? How can i use this on other files?
===header.h===
#ifndef HDR_H
#define HDR_H
extern int x;
void function();
#endif
===header.c===
#include <stdio.h>
#include "header.h"
void function()
{
printf("%d", x); //****undefined reference to x, why?****
}
===sample.c===
int main()
{
int x = 1;
function();
printf("\n%d", x);
return 0;
}
c file. The error: undefined reference to function show() has appeared on the terminal shell as predicted. To solve this error, simply open the file and make the name of a function the same in its function definition and function call.
If you get an error about "undefined reference" when compiling a program of your own from source code, then you are probably missing to include some required symbols which should be distributed in a separate library archive. To find which archive to include we can use the tools "readelf" and "nm".
This error is often generated because you have typed the name of a function or variable incorrectly. For example, the following code: #include <stdio.h> void print_hello() { printf ("Hello!\n"); } /* To shorten example, not using argp */ int main() { Print_hello(); return 0; }
Linker Errors: These error occurs when after compilation we link the different object files with main's object using Ctrl+F9 key(RUN). These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files.
The declaration
extern int x;
tells the compiler that in some source file there will be a global variable named x
. However, in the main
function you declare a local variable x
. Move that declaration outside of main
to make it global.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With