Undefined character error when using header file

I get the following error and for my whole life I canโ€™t understand what I'm doing wrong.

$ gcc main.c -o main Undefined symbols: "_wtf", referenced from: _main in ccu2Qr2V.o ld: symbol(s) not found collect2: ld returned 1 exit status 

main.c:

 #include <stdio.h> #include "wtf.h" main(){ wtf(); } 

wtf.h:

 void wtf(); 

wtf.c:

 void wtf(){ printf("I never see the light of day."); } 

Now, if I include the entire function in the header file, and not just the signature, it meets the requirements, so I know that wtf.h is included. Why does the compiler not see wtf.c? Or am I missing something?

Sincerely.

+4
source share
2 answers

You need to associate wtf with your main . The easiest way to compile it is gcc will link them for you, for example:

 gcc main.c wtf.c -o main 

Longer path (separate wtf compilation):

 gcc -c wtf.c gcc main.c wtf.o -o main 

Even longer (separate compilation and binding)

 gcc -c wtf.c gcc -c main.c gcc main.o wtf.o -o main 

Instead of the last call to gcc you can run ld directly with the same effect.

+10
source

You are missing the fact that simply including a header does not tell the compiler anything about where the actual implementation (definition) of things declared in the header is.

They can be in the C file next to the one that include does, they can come from a pre-compiled static link library or a dynamic library loaded by the system linker when reading your executable file, or they can run (for example, the dlopen() function on Linux, eg).

C is not like Java, there is no implicit rule, because only because the C file contains a specific header, the compiler must also do something to โ€œmagicallyโ€ find an implementation of the things declared in the header. You have to say it.

+4
source

Source: https://habr.com/ru/post/1311832/


All Articles