Perfect solution to MacOS error about ld: library not found for -lnetcdff

1. Problem description 

An error occurred when compiling a program using the Intel version of Mac, as shown below.
Note: libnetcdff is the Fortran interface of netcdf, as explained by ChatGPT below. 

2. Reasons for occurrence

The reason is that the static library link defined in the Makefile is not found in the system's default library path, which is such as /usr/lib, /lib or /usr/local/lib. The picture below shows the error part in the Makefile. You can see that NETCDF_PATH is not defined in advance, so it will directly enter the else condition to execute -lnetcdff and search in the system default library path, but the relevant files cannot be found in the system default path. So an error will be reported.

3.Solution

3.1 Method 1

Define the path to libnetcdff directly in the Makefile.

There is a pit here. On the Mac system, I used Homebrew to install netcdf. The command is as follows:

brew install netcdf

Huge pit:

But I did not find the libnetcdff library file under the lib file of netcdf! ! !
I used brew to search for available software for netcdf and found that there is also a specific netcdf-fortran version....

Back to topic:

After installing netcdf-fortran and then specifying the path to libnetcdff in the Makefile, the problem can be solved successfully.

 3.2 Method 2

You can define the search path before make, but it is only temporary and will be invalid after the next power cycle.

export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/Cellar/netcdf-fortran/4.6.0/lib

 3.3 Method 3

Copy the file libnetcdff.a to the /usr/lib directory (it may be possible on other Linux systems, but Mac has a protection mechanism and does not have permission to operate /usr/lib)

Unless SIP (System Intergerity Protection) is manually blocked, permissions are restored.

or enable the first two possible methods.

cp /usr/local/Cellar/netcdf-fortran/4.6.0/lib/libnetcdff.a /usr/lib

Guess you like

Origin blog.csdn.net/weixin_44547510/article/details/131206090