How to Check If a Function Exists in C/C++

How to check if a function exists in C/C++?

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.

How to detect if a function exists?

With declaration of

template<typename From, typename To> To convert(const From& from);

Your traits

template<typename From, typename To>
struct IsConvertible

would always detect presence of convert function.

One way to fix it is overloads and/or SFINAE:

template <typename> struct Tag{};

int convertImpl(tag<int>, const std::string& from);
float convertImpl(tag<float>, const std::string& from);
// overloads ...

template<typename From, typename To>
auto convert(const From& from)
-> decltype(convertImpl(tag<To>{}, from))
{
return convertImpl(tag<To>{}, from);
}

Use concepts to check if a global function exists

This appears to work:

template<typename T>
concept method_to_string = requires(T v)
{
{ to_string(v) } -> std::same_as<std::string>;
};

https://gcc.godbolt.org/z/7WdTjf

Can I re-define a function or check if it exists?

You can do this in GCC using its weak function attribute extension:

void func() __attribute__((weak)); // weak declaration must always be present

int main() {
if (func) func();
// ...
}

// optional definition:
void func() { ... }

This works even if func() is defined in another .c file or a library.

how to check if function exists

Your best bet is to use the standard __cplusplus macro which, for C++11, is 201103L. For C++14 onwards it will be a different value to this.

C++ Concepts for checking if a function exists in a container class and implicit deduction rules

By using a template-template parameter you already constrain your function to containers that follow the standard library pattern but also to class templates that just happen to have two type template parameters. This is a strong constraint and usually useless in practice. That is, I would suggest that you instead operate on concrete types represented by a type template parameter, and let the concept verify any requirements that you would like to impose.

Additionally, don't use decltype with std::declval with std::is_same to check validity of an expression. Concepts have a dedicated syntax for that purpose, which is just putting this expression in braces.

One solution, merging what you want to verify in a single concept, could be as below:

#include <concepts>
#include <utility>
#include <type_traits>

template <typename C, typename T>
concept PushBackMovable = requires (C c, T t) {
{ c.push_back(t) } -> std::same_as<void>;
{ c.push_back(std::move(t)) } -> std::same_as<void>;
};

template <typename T, PushBackMovable<std::remove_reference_t<T>> C>
void operator+=(C& lhs, T&& rhs)
{
lhs.push_back(std::forward<T>(rhs));
}

DEMO

How to check if a variable or function exists in std?(in c++)

There is no definitive list of names inside std - it can always be expanded, and was created exactly for that purpose. Therefore, stop using the namespace once and for all.

In other words, C++ standard prescribes what names have to be there, but by no means it limits the overall names set to those prescribed. Implementations often put a lot of other helper functions or classess into this namespace.

Templated check for the existence of a class member function?

Yes, with SFINAE you can check if a given class does provide a certain method. Here's the working code:

#include <iostream>

struct Hello
{
int helloworld() { return 0; }
};

struct Generic {};

// SFINAE test
template <typename T>
class has_helloworld
{
typedef char one;
struct two { char x[2]; };

template <typename C> static one test( decltype(&C::helloworld) ) ;
template <typename C> static two test(...);

public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};

int main(int argc, char *argv[])
{
std::cout << has_helloworld<Hello>::value << std::endl;
std::cout << has_helloworld<Generic>::value << std::endl;
return 0;
}

I've just tested it with Linux and gcc 4.1/4.3. I don't know if it's portable to other platforms running different compilers.

check if C-style function exists of type 'MyMethodName()'?

Xcode (at least since 4.3) supports weak linking and you can do the following to see if you can call a C function:

// UIGraphicsBeginImageContextWithOptions() was introduced in iOS 4 in order to support the Retina displays.
if (UIGraphicsBeginImageContextWithOptions != NULL) {
UIGraphicsBeginImageContextWithOptions(...);
}
else {
UIGraphicsBeginImageContext();
}


Related Topics



Leave a reply



Submit