Search code examples
c++functionmodularity

Code usability in c++


Is it possible to write a function in a file and then use it inside code that is contained in another file ? I am using c++ . If it is,can anyone give an example ? Thanks !


Solution

  • Yes of course it is. How to make it happen depends on what these two files are (header files or main code files). Let's call them function_defined.___ and function_used.___.

    There are two cases, depending on what each is.

    • function_defined.hpp

      The simplest case -- In function_defined.hpp, put

      int funct(int argument) {return 1}
      

      and in function_used.(c/h)pp, just

      #include "function_defined.hpp"
      ...
      int c = funct(1);
      
    • function_defined.cpp

      In this case, you first need a declaration in function_used.(c/h)pp :

      int funct(int argument);
      

      You can call the function just like above. Do not do #include "function_defined.cpp". You should just compile all the .cpp files and link them together, which automatically finds and links the desired function.

    As Omnifarious said, the details of compiling and linking depend on your platform and IDE and/or compiler.