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?

8
  • Why don't you use #include "header.h" in sample.c? Commented Feb 12, 2015 at 10:34
  • Then why you're compiling and linking it? :-) Commented Feb 12, 2015 at 10:35
  • 1
    @CoderGuy You're not supposed to compile headers in the first place. Commented Feb 12, 2015 at 10:41
  • @biffen i got it from here: stackoverflow.com/questions/2831361/… Commented Feb 12, 2015 at 10:45
  • @CoderGuy And which part of that told you to compile a header file? Commented Feb 12, 2015 at 10:47

3 Answers 3

10

Good and the right way would be to

sample.c

#include "header.h" 

and compile

gcc sample.c -o ob 
Sign up to request clarification or add additional context in comments.

15 Comments

How would that be in geany (Build and compile commands). that would be easyer
what does the f2.c and f1.c stand for? in geany build commands it's all like "%f" and stuff
@CoderGuy Let me not confuse you please include the header in .c file compile and run..
but the header is a .h file
@CoderGuy There you go!! Please use #include "header.h" .. Use double quotes instead of < > brackets
|
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

3 Comments

@CoderGuy Sorry, no. But how that is related to this?
@CoderGuy Your issue has nothing to do with the geany or anything. Kindly correct the actions, it'll work. :-)
@Biffen Whoops !! Typo. Thanks.
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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.