使用g ++进行动态共享库编译 [英] Dynamic Shared Library compilation with g++
问题描述
我正在尝试从 Program-Library-HOWTO中编译以下简单的DL库示例代码与g ++。这只是一个例子,所以我可以学习如何使用和写共享库。我正在开发的库的实际代码将用C ++编写。
I'm trying to compile the following simple DL library example code from Program-Library-HOWTO with g++. This is just an example so I can learn how to use and write shared libraries. The real code for the library I'm developing will be written in C++.
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("/lib/libm.so.6", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
}
如果我用gcc编译程序工作正常。
If I compile the program with gcc it works fine.
gcc -o foo foo.c -ldl
当我将文件名和编译器更改为以下
When I change the filename and compiler to the following
g++ -o foo foo.cpp -ldl
我得到以下错误:
foo.cpp:16:错误:从'void *'到'double(*)(double)'的无效转换
foo.cpp:16: error: invalid conversion from 'void*' to 'double (*)(double)'
我理解(我我的理解,纠正我,如果这是错误的),我不能做一个隐式转换从C ++中的void指针,但C让我和这个是为什么上面的代码将使用gcc编译而不是使用g ++。所以我试图通过改变上面的行16显式转换:
I understand (I think I understand, correct me if this is wrong) that I can't do an implicit cast from a void pointer in C++, but C lets me, and this is why the above code will compile using gcc but not using g++. So I tried an explicit cast by changing line 16 above to:
cosine = (double *)dlsym(handle, "cos");
有了这个,我得到以下错误:
With this in place, I get the following error:
foo.cpp:16:错误:无法在赋值
foo.cpp:16: error: cannot convert 'double*' to 'double (*)(double)' in assignment
这些问题可能与我自己对正确的C ++编码标准的一般忽略有关。任何人都可以指点一个关于开发使用C ++示例代码的Linux动态库的好教程。
These problems probably have more to do with my own general ignorance of proper C++ coding standards than anything else. Can anyone point me to a good tutorial on developing dynamic libraries for Linux that uses C++ example code?
推荐答案
void *
到任何指针类型(包括函数指针); C ++需要显式转换。正如leiflundgren所说,你需要把 dlsym()
的返回值转换成你需要的函数指针类型。
C allows implicit casts from void *
to any pointer type (including function pointers); C++ requires explicit casting. As leiflundgren says, you need to cast the return value of dlsym()
to the function pointer type you need.
很多人发现C的函数指针语法尴尬。一个常见的模式是typedef函数指针:
Many people find C's function pointer syntax awkward. One common pattern is to typedef the function pointer:
typedef double (*cosine_func_ptr)(double);
您可以定义函数指针变量 cosine
作为您的类型的成员:
You can define your function pointer variable cosine
as a member of your type:
cosine_func_ptr cosine;
使用类型而不是awkward函数指针语法进行转换:
And cast using the type instead of the awkward function pointer syntax:
cosine = (cosine_func_ptr)dlsym(handle, "cos");
这篇关于使用g ++进行动态共享库编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!