Search code examples
ccompiler-errorsundefined-referencefunction-declaration

How exactly linking works and what exactly i am doing wrong here


I am new to C and multi source files code. I have a header file prog.h and source file prog.c in those name and age are declared using extern keyword with set_data and print_data are accessing them in main.c. But it showing some linking error. What exactly i am doing wrong here?

prog.h

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>

#define ERROR(s) perror(s)
#define BUFF 1024

extern char* name;
extern int age;

void print_data(char* name, int age);` 

prog.c

#include "prog.h"

void set_data(char* a_name, int a_age)
{
    name = a_name;
    age = a_age;
}

void print_data(char *name, int age)
{
    printf("Name: %s\nAge: %d\n", name, age);
}

main.c

#include "prog.h"
#include <stdlib.h>

int main(int argc, char **argv)
{
    set_data(argv[1], argv[2]);
    print_data(name, age);
    return EXIT_SUCCESS;
}

GCC:

gcc -o main main.c prog.c

Error:

`main.c: In function ‘main’:
main.c:6:5: warning: implicit declaration of function ‘set_data’ [-Wimplicit-function-declaration]
    6 |     set_data(argv[1], argv[2]);
      |     ^~~~~~~~
/usr/bin/ld: /tmp/ccWK8fek.o: warning: relocation against `name' in read-only section `.text'
/usr/bin/ld: /tmp/ccR60C2Q.o: in function `main':
main.c:(.text+0x3b): undefined reference to `age'
/usr/bin/ld: main.c:(.text+0x42): undefined reference to `name'
/usr/bin/ld: /tmp/ccWK8fek.o: in function `set_data':
prog.c:(.text+0x16): undefined reference to `name'
/usr/bin/ld: prog.c:(.text+0x1f): undefined reference to `age'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status

I have researched online, i have tried using extern keyword but, it's not working.


Solution

  • These declarations of variables

    extern char* name;
    extern int age;
    

    are not their definitions. So the compiler issues messages that references to the variables are undefined. You need to define them for example in prog.c like

    char* name;
    int age;
    

    The declaration of the function set_data is absent in the translation unit with main. So the compiler issues messages that the function is implicitly declared. Without seeing its declaration the compiler is unable to check whether the function is used correctly. Place the function declaration in thhe header prog.h the same way as the function declaration of print_data.