如何检查是否在C / C存在功能++ [英] How to Check if the function exists in C/C++

查看:92
本文介绍了如何检查是否在C / C存在功能++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的code某些情况下,我最终调用只有在该函数定义的功能,不然我不应该。我怎样才能做到这一点?

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.

推荐答案

而其他的答复是有帮助的建议(则dlsym ,函数指针,...),您不能编译 C ++ code指的是不存在的函数。一个极小的函数必须的 的声明;如果不是,你的code将无法编译。如果没有(编译单元,某些目标文件,某些库)的定义的功能,链接器会抱怨(除非它是弱,见下文)。

While other replies are helpful advices (dlsym, function pointers, ...), you cannot compile a C++ code referring to a function which does not exist. A minima, 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.

注意 则dlsym 往往需要的功能,而不名称重整,即声明为的externC

如果编码在Linux上使用GCC,你可能也使用函数属性的声明。然后链接器将设置未定义的弱符号为null。

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.

如果您是从一些输入获取函数名,你应该知道,只有一部分功能应该是可调用这种方式(如果调用无牵挂的任意函数,它会崩溃!),你会更明确构建一个子集。然后,您可以使用的std ::地图则dlsym (与中声明的子集中的每个功能为externC)。请注意,的dlopen NULL 路径给出了一个手柄主程序,你应该用<$ C $链接C> -rdynamic 来把它正常工作。

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。如果你知道的动态的被调用函数的签名,您可能需要使用 libffi 调用它。

NB. If you know dynamically the signature of the called function, you might want to use libffi to call it.

这篇关于如何检查是否在C / C存在功能++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆