Reputation: 2785
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?
Upvotes: 1
Views: 1405
Reputation: 10487
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;
}
Upvotes: 2
Reputation: 405
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.
Upvotes: 2
Reputation: 272247
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.
Upvotes: 6
Reputation: 81384
#include
the source file with the other function's declaration.
Upvotes: 2