Certain situations in my code, i end up invoking the function only if that function is defined, or else i should not. How can i achieve this ?
like: if (function 'sum' exists ) then invoke sum ()
May be the other way around to ask this question is: How to determine if function is defined at runtime and if so, then invoke.
When you declare 'sum' you could declare it like:
#define SUM_EXISTS int sum(std::vector<int>& addMeUp) { ... }
Then when you come to use it you could go:
#ifdef SUM_EXISTS int result = sum(x); ... #endif
I'm guessing you're coming from a scripting language where things are all done at runtime. The main thing to remember with C++ is the two phases:
So all the #define
and things like that happen at compile time.
....
If you really wanted to do it all at runtime .. you might be interested in using some of the component architecture products out there.
Or maybe a plugin kind of architecture is what you're after.
While other replies are helpful advices (dlsym
, function pointers, ...), you cannot compile C++ code referring to a function which does not exist. At minimum, the function has to be declared; if it is not, your code won't compile. If nothing (a compilation unit, some object file, some library) defines the function, the linker would complain (unless it is weak, see below).
But you should really explain why you are asking that. I can't guess, and there is some way to achieve your unstated goal.
Notice that dlsym
often requires functions without name mangling, i.e. declared as extern "C"
.
If coding on Linux with GCC, you might also use the weak
function attribute in declarations. The linker would then set undefined weak symbols to null.
If you are getting the function name from some input, you should be aware that only a subset of functions should be callable that way (if you call an arbitrary function without care, it will crash!) and you'll better explicitly construct that subset. You could then use a std::map
, or dlsym
(with each function in the subset declared extern "C"
). Notice that dlopen
with a NULL
path gives a handle to the main program, which you should link with -rdynamic
to have it work correctly.
You really want to call by their name only a suitably defined subset of functions. For instance, you probably don't want to call this way abort
, exit
, or fork
.
NB. If you know dynamically the signature of the called function, you might want to use libffi to call it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With