use*_*505 2 c gcc fortran gfortran
在C中使用GCC,可以使用以下函数在加载共享库时调用一些代码:
static void __attribute__((constructor)) _my_initializer(void)
{
...
}
Run Code Online (Sandbox Code Playgroud)
在网上进行一些搜索后,我无法在Fortran中找到使用GCC(即gfortran)的等效文件.确保此功能必须存在于gfortran中,因为它来自GCC(因此它应该以GCC支持的所有语言提供).有什么指针吗?
"肯定这个功能必须存在于gfortran中,因为它来自海湾合作委员会"这显然是错误的.它根本就不存在.gfortran支持该!GCC$ ATTRIBUTES指令,但支持的属性数量有限.
您可以在C中编写构造函数,并让它成为同一个库的一部分,并调用您想要的任何Fortran代码.
例:
library.f90:
subroutine sub() bind(C)
write(*,*) "Hello!"
end subroutine
Run Code Online (Sandbox Code Playgroud)
init_library.c:
void sub(void);
static void __attribute__((constructor)) _init(void)
{
sub();
}
Run Code Online (Sandbox Code Playgroud)
load_library.c:
#include <stdio.h>
#include <unistd.h>
#include <dlfcn.h>
typedef void (*foo)(void);
int main(int argc, char* argv[])
{
void *lib = dlopen("library.so", RTLD_NOW);
if(lib == NULL)
return printf("ERROR: Cannot load library\n");
dlclose(lib);
}
Run Code Online (Sandbox Code Playgroud)
编译并运行:
> gfortran -c -fPIC init_library.c
> gfortran -c -fPIC library.f90
> gfortran -shared library.o init_library.o -o library.so
> gfortran load_library.c -ldl
> ./a.out
Hello!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |