0

When I try to access a variable or a function with extern, I get the error of 'undefined reference to'.

All what I am trying to do is add id 1 to an integer variable using a function (file 1) and it works and then I declared another variable in (file 2) and I try to access the function and the variable of the (file 1) from the (file 2) so i can change the value of the new variable based on the function and the first variable. I know that the program dont make sens but I am just trying to practice what I am learning

This is the file 2.

#include <stdio.h>

extern int increment();
extern int count;

int main() 
{
    int value;
    value= increment();
    value=count+3;
    return 0;
}

And this is file 1

#include <stdio.h>

int count = 0;
int increment() 
{
    count=count+1;
    printf("%d",count);
    return count;
}

int main()
{
    increment();
    return 0;
}

When I run the code I get this error:

C:\Users\RIB~1\AppData\Local\Temp\cc6L4Qk8.o:main.c:(.text+0xf): undefined reference to `increment'
C:\Users\RIB~1\AppData\Local\Temp\cc6L4Qk8.o:main.c:(.text+0x18): undefined reference to `count'
collect2.exe: error: ld returned 1 exit status
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 1
    Are you specifying both object files on the linking command line? – Jonathan Leffler Mar 23 '23 at 10:12
  • Welcome to SO. There is a misconception. You are not running your code. You try to compile it which fails. You cannot run any program if compilation fails. – Gerhardh Mar 23 '23 at 10:19
  • How do you compile? – Jabberwocky Mar 23 '23 at 10:20
  • Get a decent programming IDE. Add all source files to the same project. Create a header file corresponding to "file2.c" or whatever it is called. Create setter/getter functions. Never use `extern` anywhere in your C source. Never use obsolete style `()` functions in your C source. – Lundin Mar 23 '23 at 10:38

0 Answers0