开发者

function header and implementation in different files C

开发者 https://www.devze.com 2023-02-22 10:21 出处:网络
How do you have a header file for a function and the implementation of that function indifferent files? Also, how do you have main in yet another file and call thisfunction?

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?


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'


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.


In C/C++, non-inline functions should be defined only once. If you put function defination in header files, you will get "multiple defination" link error when the header file is included more than once.

0

精彩评论

暂无评论...
验证码 换一张
取 消