c - 如何将一个 .c 文件中定义的结构填充到另一个 .c 中定义的函数中,而不将指针作为参数传递?

标签 c pointers struct fortran extern

我有一个 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/

相关文章:

c - 如何在不导致段错误的情况下更新 bst 结构中的字符指针?

c - 为什么不添加对纯 C 的模板支持?

c - 是否有理由不键入强制转换指针 (C)?

c - 编写并使用一个将掩码作为参数并返回结构的函数

c - 输入空格

c++ - C 中 printf() 函数的工作(仅可变数量的参数)

c - 确保只将指针传递给可变参数函数

c - 连续二维数组的重新分配

c++ - 我应该在头文件或源文件中实现带有构造函数的结构吗?

c - 如何将解压结构的内容复制到 __packed__ 结构?