Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C header issue: #include and "undefined reference"

Alright, I've been trying to work with this for the longest time, and I simply can't seem to get it to work right. I have three files, main.c, hello_world.c, and hello_world.h. For whatever reason they don't seem to compile nicely, and I really just can't figure out why...

Here are my source files. First hello_world.c:

#include <stdio.h> #include "hello_world.h"  int hello_world(void) {   printf("Hello, Stack Overflow!\n");   return 0; } 

Then hello_world.h, simple:

int hello_world(void); 

And then finally main.c:

#include "hello_world.h"  int main() {   hello_world();   return 0; } 

When I put it into GCC, this is what I get:

 cc     main.c   -o main /tmp/ccSRLvFl.o: In function `main': main.c:(.text+0x5): undefined reference to `hello_world' collect2: ld returned 1 exit status make: *** [main] Error 1 

Anyone able to help me out? I'm really stuck on this, but I'm 99 percent sure it's a really simple fix.

like image 562
user1018501 Avatar asked Apr 27 '12 20:04

user1018501


People also ask

What are C headers?

Advertisements. A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.

Is header file necessary in C?

Yes, because it's still based on C. You can answer your own question: Don't use them and try to compile without them. If you can't, then the compilers still require them.

What is the purpose of C header files?

A header file is a file containing C declarations and macro definitions (see Macros) to be shared between several source files. You request the use of a header file in your program by including it, with the C preprocessing directive ' #include '.

Can C program run without header file?

Yes you can wirte a program without #include , but it will increase the complexity of the programmer means user have to write down all the functions manually he want to use.It takes a lot of time and careful attention while write long programs.


2 Answers

gcc main.c hello_world.c -o main 

Also, always use header guards:

#ifndef HELLO_WORLD_H #define HELLO_WORLD_H  /* header file contents go here */  #endif /* HELLO_WORLD_H */ 
like image 126
Lundin Avatar answered Nov 09 '22 22:11

Lundin


You are not including hello_world.c in compilation.

   gcc hello_world.c main.c   -o main 
like image 28
P.P Avatar answered Nov 09 '22 21:11

P.P