Pergunta

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 !

Foi útil?

Solução

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.

Outras dicas

This is trivial to accomplish and a basic part of writing any C++ program of any complexity. The details of how you do it can vary a bit depending on which platform you're on. But, all of them are variants of the same basic abstract procedure.

You have to declare your function in a header file, and you have to include that header file in each source file that either uses or defines the function. Then you have to compile each source file and link the resulting 'object' files together into an executable.

In order to give more specific detail than that you will have to be specific about your platform. Is it Visual Studio? Is it g++ on a Linux box?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top