我有一个 C 函数(store_mode_ - 在 file_A.c 中定义),它在 Fortran 代码中调用。
看起来像这样..
// Create a global structure to populate with current mode frequencies
struct minos_modes current_modes;
static int nmode = 0;
void
store_mode_( int *n, int *l, double *w, double *U )
{
if ( nmode == MODE_MAX )
{
printf( "[ store_mode_ ] Error: MODE_MAX is too small\n" );
exit( 1 );
}
current_modes.mode_n[nmode] = *n;
current_modes.mode_l[nmode] = *l;
current_modes.mode_w[nmode] = *w;
current_modes.mode_U[nmode] = *U;
nmode += 1;
current_modes.len = nmode;
}
我试图用 Fortran 调用中作为参数传递的值 (n、l、w、U) 填充结构。上面的代码在 File_B.c 中的 main 上方定义时有效,它调用其中的 fortran 代码。
但是..如果我在 file_A.c 中定义上述函数(main 不在其中),它就不起作用。我明白这是由于 .c 文件之间缺乏共享全局变量造成的。我想知道这个问题是否有解决方案? 也许与 extern 一起,尽管我玩了一点但没有成功。
最佳答案
static int nmode = 0;
如果您在两个文件中都包含该行,那么您就有两个 nmode
变量,每个文件中都有一个。 static
使符号对翻译单元私有(private)。
相反,您可能想要
int nmode;
在一个文件中,并且
extern int nmode;
在另一个。 (不需要显式地将其初始化为零。这是静态存储的保证。)
关于c - 如何将一个 .c 文件中定义的结构填充到另一个 .c 中定义的函数中,而不将指针作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37900042/