C-interoperable global variables

In C, if you have a file containing just int something;, you’ve created a variable and allocated space in the object file for it (at least I think you have). If instead you write extern int something;, you don’t create space in the object file, the symbol has to be resolved at link time (some other object file needs to provide the variable).

Suppose you’re writing a mixed Fortran/C program and you have a global variable on the C side that you want to access from Fortran. The following works, I’ve tested it, but I don’t know why it works.

Fortran file:

module stuffmod
    use iso_c_binding
    implicit none
    integer(c_int), bind(c, name="something") :: something_f
end module
program test
    use stuffmod
    implicit none
    print *, something_f
end program

C file:

int something = 10;

How does the compiler know that something_f is, effectively, extern? What would I do instead if I wanted to create a global variable in the fortran object file, and access it from C using a declaration like extern int something?


1 Like

Thanks, that does help. The key takeaway for me is that an explicit “extern”-like qualifier is not required in Fortran, and the linker just makes the right thing happen.

1 Like