C: Linking error for function of same signature

Viewed 59

I am getting a linking error when i run my program, even though the function signature is the same for both functions in test.h and test.c :

test.h :

void function(int);

test.c :

#include "test.h"
#include "stdio.h"

static void function(int n) {
    printf("%d\n", n);
}

main.c :

#include "test.h"

int main() {

    function(5);
    return 0;
}

this is the output:

Undefined symbols for architecture x86_64:
  "_function", referenced from:
      _main in ccNaA2H2.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status

In class, I learned that the function signature is the function name and its parameters. So, why doesn't my program in main call function(5) in test.h which will call the function(5) in test.c ?

Thank you

2 Answers

static at global scope (outside of functions) means that it is only visible in this file (It has internal linkage). So, the static void function(int n) in test.c is not visible from main.c.

For the call function(5); in main, the compiler sees the function prototype in test.h, but the linker cannot find an implementation of it, because the function in the c file is static.

Solution: remove the word static, if you want to use the function in a different file.

In test.c you declared your function as static which means, it will not be visible outside that module. Remove the static keyword.

Related