Home > Backend Development > C++ > body text

How to Link Fortran and C Binaries Using GCC: A Guide to Resolving Undefined Reference Errors?

Barbara Streisand
Release: 2024-10-27 03:49:29
Original
760 people have browsed it

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>
Copy after login
<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>
Copy after login

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
Copy after login

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++
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!