Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check if the function exists in C/C++

Tags:

c++

c

linux

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.

like image 629
Whoami Avatar asked Jan 11 '12 05:01

Whoami


2 Answers

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:

  • Compile time
    • Preprocessor runs
    • template code is turned into real source code
    • source code is turned in machine code
  • runtime
    • the machine code is run

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.

like image 91
matiu Avatar answered Sep 19 '22 14:09

matiu


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.

addenda

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.

like image 40
Basile Starynkevitch Avatar answered Sep 17 '22 14:09

Basile Starynkevitch