1

how can one called function in c++ program where function is declared in other c++ program? how can one do this? can i use extern?

bunty
  • 2,665
  • 8
  • 30
  • 27

4 Answers4

7

I would suggest the best way is to refactor the first C++ program such that the required function is made part of a library. Then both your programs can link to that library and the function is available to both (and to any other programs requiring it).

Take a look at this tutorial. It covers how to create and then use a library using gcc. Other similar tutorials will exist for other C++ variants.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
3

If you mean programs as 'processes', it depends on the os you are running your programs. In most cases you can't easily (if at all), because the processes would have to share memory. In debug versions of the some os's this might be possible. In a few words: if you mean that you want to call a function in the code of a running program from another program, this is very difficult and VERY system depended.

frag
  • 415
  • 2
  • 6
2

#include the source file with the other function's declaration.

Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
2

Declared or defined? The important thing to bear in mind is that before using a function, the compiler needs to be aware of function prototype so use #include to ensure that the compiler has access to the prototype. It doesn't need the actual code for the function necessarily, that becomes important at link time.

So, if you have:

MyFunc.hpp:

int add( int a, int b);

MyFunc.cpp:

int add( int a, int b)
{
    return a + b;
}

Then you can use this in another file:

Main.cpp

#include <iostream>
#include <MyFunc.hpp>  // This is the important bit. You don't need the .cpp

int main( int argc, char* argv[] )
{
    std::cout << add( 20, 30 ) << std::endl;
}
Component 10
  • 10,247
  • 7
  • 47
  • 64