Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function header and implementation in different files C

How do you have a header file for a function and the implementation of that function in different files? Also, how do you have main in yet another file and call this function? The advantage is so that this function will then be an independent component which can be reused, right?

like image 736
Namratha Avatar asked Aug 23 '26 00:08

Namratha


2 Answers

This is best illustrated by an example.

Say we want a function to find the cube of an integer.

You would have the definition (implementation) in, say, cube.c

int cube( int x ) {
  return x * x * x;
}

Then we'll put the function declaration in another file. By convention, this is done in a header file, cube.h in this case.

int cube( int x );

We can now call the function from somewhere else, driver.c for instance, by using the #include directive (which is part of the C preprocessor) .

#include "cube.h"

int main() {
  int c = cube( 10 );
  ...
}

Finally, you'll need to compile each of your source files into an object file, and then link those to obtain an executable.

Using gcc, for instance

$ gcc -c cube.c                 #this produces a file named 'cube.o'
$ gcc -c driver.c               #idem for 'driver.o'
$ gcc -o driver driver.c cube.c #produces your executable, 'driver'
like image 130
abeln Avatar answered Aug 25 '26 21:08

abeln


Actually you can implement any function in header files for better performance(when implementing libraries for example) as long are not referenced to a specific object(actually it won't compile that). By the way even with that way, you have separate interface and implementation ;) Of course you will have include gurads in you header files to avoid "multiple definition" errors.

like image 32
filippos Avatar answered Aug 25 '26 20:08

filippos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!