C++ – C\C++ – Re-using functions across multiple programs

c

In Python whenever I had a bunch of functions that I wanted to use across multiple programs I'd make another .py file and then just import that wherever I needed it. How would I do that in C/C++? Do I dump both prototype and implementation into an .h file? or do I need to place the function prototypes in the .h file and the implementations in a separate .cpp file with the same name as the .h file and #include the .h wherever I need it?

Best Answer

You need to do a couple of things:

  1. Add the prototype to a header file.
  2. Write a new source file with the function definitions.
  3. In a source file that just wants to use the shared function, you need to add #include "header.h" (replacing header.h with the name of the file from step 1) someplace before you try to call the shared function (normally you put all includes at the top of the source file).
  4. Make sure your build compiles the new source file and includes that in the link.

A couple of other comments. It's normal to have foo.h as the header for the foo.c but that is only a style guideline.

When using headers, you want to add include guards to protect against the multiple include issue.