call a function from header file in C

59 Views Asked by At

In xv6, I have hello.h inside kernel folder, main.c inside user folder. The error is in main.c.

kernel/hello.h:

void hello();

kernel/hello.c:

void hello(){
    printf("hello\n);
}

Now I want to call function hello(). But get error.

user/main.c:

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/hello.h"

int main(int argc, char *argv[]) {
  hello(); // error here (undefined reference to `hello')
  exit(0);
}
2

There are 2 best solutions below

0
gulpr On BEST ANSWER

You need to compile hello.c and main.c files and link them together.

gcc -o myprog main.c hello.c

./myprog
0
NRagot On

undefined reference error usually occurs when a symbol is known to the linker but fails to be associated to an actual definition.

in the context of main.c, hello was known. The compiler is happy because it's compiling main.c and so doesn't need to know the specifics of hello. But the linker does, because it's job is to make the different pieces fit together.

Make sure you have compiled both files main.c and hello.c and that both are known to the linker stage (with gcc, it's whenever you do not compile with the -c flag).

For instance, it could be

gcc main.c  -c -o main.o
gcc hello.c -c -o hello.o
gcc main.o hello.o -o a.out

or even, because gcc is pretty lenient : gcc main.c hello.c