'how do i call a function in my program from a shared library [closed]
i would like to call a function inside my main program from a shared library at runtime without dropping performance
main program:
using namespace std;
int b = 2;
// it must be called from the library
void func1(int a) {
b = b + a;
}
void func2();
int main() {
func2(); // call "func2" in my shared library
cout<<"Value: " << b << endl;
return 0;
}
my library:
void somefunc(int a);
void func2() {
func1(5); // Call "func1" in the main program
}
Solution 1:[1]
The solution here is to not define them all in the main.cpp
file, but instead split them out. Convention has it that you have a .h
(or .hpp
if you prefer) header file that has the function declarations (signatures) for anything shared, and then the .cpp
file contains the definitions (implementations) of them.
That is you'd have:
// functions.h
void func1(int a);
void func2();
Then move the implementations to the corresponding functions.cpp
.
Then it's as easy as:
#include "functions.h"
func1(0);
Although there's many ways to organize your files, I'd recommend not putting a lot of "stuff" in your main.cpp
, but instead keep that as high-level a possible. Anything remotely complicated should be compartmentalized inside a function and that can be defined in another file.
If you have a "heavy" main.cpp
then your compile times will get slower and slower as you pile more code into it. When you separate things only the changed dependencies need to get rebuild, so if you have 20 .cpp
files and only change 1, then you only need to recompile 1.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tadman |