Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Undefined reference

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;
}
like image 690
Analyn Avatar asked Aug 08 '12 09:08

Analyn


People also ask

How do you fix undefined references in c?

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.

What is meant by undefined reference in c?

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".

What is undefined reference to printf in c?

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; }

What is linking error in c?

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.


1 Answers

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.

like image 166
Some programmer dude Avatar answered Sep 21 '22 23:09

Some programmer dude