5

I have made a header and a source but I don't know how to link them up. I looked it up on the web but the commands provided didn't work (or I wouldn't be here :) ).

To compile it (if you use GCC):

Header:

$ gcc -c whatever.h -o whatever.o

Source:

$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

What did I do wrong. I am using geany for writing (compile error is here) but the commands are executed on a terminal in the same directory. can anybody give me the build commands for geany so whenever I want to include a header I can just compile and run?

BRHSM
  • 854
  • 3
  • 13
  • 48

3 Answers3

8

Good and the right way would be to

sample.c

#include "header.h"

and compile

gcc sample.c -o ob
Gopi
  • 19,784
  • 4
  • 24
  • 36
4

Thumb Rule:

  • header files [.h] are for #includeing
  • source files [.c] are for compiling and linking together to create the executable.

Once you've #included your header file in a .c file, there's no need to compile the header file and produce an object file.

FYI, you can check the effect of #include-ing the header file by running

gcc -E sample.c

and hope you'll understand why you need not compile and link the header file separately.


EDIT:

if you have a sample.c and whatever.h, to produce and run the binary, simply do

  • #include "whatever.h" in the top of sample.c

  • gcc -o sample sample.c

  • ./sample

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

if you include header file by:

#include <header.h>

it will give this error.

Instead you can write as given below:

#include "header.h"
Shiv Buyya
  • 3,770
  • 2
  • 30
  • 25