Home >Backend Development >C++ >How to Link Fortran and C Binaries Using GCC: A Guide to Resolving Undefined Reference Errors?
Linking Fortran and C Binaries Using GCC
Linking projects that use both Fortran and C code can be challenging due to the incompatibilities between the associated libraries. When attempting to compile and link such projects using g or gfortran, undefined reference errors often occur.
For instance, consider the following code:
<code class="fortran">subroutine print_hi() bind(C) implicit none write(*,*) "Hello from Fortran." end subroutine print_hi</code>
<code class="cpp">#include <iostream> extern "C" void print_hi(void); using namespace std; int main() { print_hi(); cout << "Hello from C++" << endl; return 0; }</code>
Compiling these files with g or gfortran separately produces object files, but linking them together using g results in undefined references to Fortran libraries. Similarly, using gfortran results in undefined references to C libraries.
To resolve this issue, it is necessary to link in the appropriate libraries during the linking stage. For g , this can be achieved by adding the -lgfortran flag to the link command:
g++ main.o print_hi.o -o main -lgfortran
This flag will link in the necessary Fortran libraries. Alternatively, gfortran can be used with the -lstdc flag to link in the required C libraries:
gfortran main.o print_hi.o -o main -lstdc++
By specifying the appropriate linking flags, programmers can successfully link projects that combine Fortran and C code, allowing them to leverage the capabilities of both languages in their applications.
The above is the detailed content of How to Link Fortran and C Binaries Using GCC: A Guide to Resolving Undefined Reference Errors?. For more information, please follow other related articles on the PHP Chinese website!