此问题在此处已有答案:
What is an undefined reference/unresolved external symbol error and how do I fix it?(38个答案)
昨天关门了。
我只想在我的Ubuntu 22.04系统中使用系统打包的g++11.3.0版编译这个简单的GDAL library示例:
#include <iostream>
#include "gdal_priv.h"
#include "cpl_conv.h"
#include "gdal.h"
using namespace std;
int main(int argc, char* argv[])
{
GDALDataset *poDataset;
GDALAllRegister();
poDataset = (GDALDataset *) GDALOpen(argv[1], GA_ReadOnly);
if (poDataset == NULL)
{
cout << "No dataset loaded for file " << argv[1] << ". Exiting." << endl;
return 1;
}
cout << "Driver: "
<< poDataset->GetDriver()->GetDescription()
<< "/"
<< poDataset->GetDriver()->GetMetadataItem(GDAL_DMD_LONGNAME)
<< endl;
cout << "Size: "
<< poDataset->GetRasterXSize() << "x"
<< poDataset->GetRasterYSize() << "x"
<< poDataset->GetRasterCount()
<< endl;
if (poDataset->GetProjectionRef() != NULL)
{
cout << "Projection: " << poDataset->GetProjectionRef() << endl;
}
}
当然,我安装了GDAL库,如这里所示:
~$ dpkg -l | grep gdal
ii gdal-bin 3.4.1+dfsg-1build4 amd64 Geospatial Data Abstraction Library - Utility programs
ii gdal-data 3.4.1+dfsg-1build4 all Geospatial Data Abstraction Library - Data files
ii libgdal-dev 3.4.1+dfsg-1build4 amd64 Geospatial Data Abstraction Library - Development files
ii libgdal30 3.4.1+dfsg-1build4 amd64 Geospatial Data Abstraction Library
ii python3-gdal 3.4.1+dfsg-1build4 amd64 Python 3 bindings to the Geospatial Data Abstraction Library
一切似乎都已经安排妥当,可以开始了,但是,当我触发这个g++
命令来编译我的小程序时g++ -I/usr/include/gdal -L/usr/lib -lgdal open_file.cpp -o open_file -g
它将失败,并显示以下输出:
/usr/bin/ld: /tmp/ccU6PwuP.o: in function `main':
/home/jose/Code/concepts/gdal/open_file.cpp:13: undefined reference to `GDALAllRegister'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:14: undefined reference to `GDALOpen'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:29: undefined reference to `GDALDataset::GetRasterXSize()'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:30: undefined reference to `GDALDataset::GetRasterYSize()'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:31: undefined reference to `GDALDataset::GetRasterCount()'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:34: undefined reference to `GDALDataset::GetProjectionRef() const'
/usr/bin/ld: /home/jose/Code/concepts/gdal/open_file.cpp:36: undefined reference to `GDALDataset::GetProjectionRef() const'
collect2: error: ld returned 1 exit status
这没有任何意义,因为我确实在-I/usr/include/gdal
中传递GDAL库,并且“未定义”引用的定义确实存在于那里的多个.h
文件中。
此外,**使用clang++**进行以下操作:clang++ -I/usr/include/gdal -L/usr/lib -lgdal open_file.cpp -o open_file -g
有没有人有类似的问题,或者可以给出一些提示,问题可能在哪里?谢谢。
1条答案
按热度按时间m1m5dgzv1#
-I/usr/include/gdal -L/usr/lib
都不是必需的,因为它们是默认设置的。但是你应该使用#include <gdal/gdal.h>
,而不仅仅是<gdal.h>
,当然也不是"gdal.h"
。-lgdal
移到所有其他cpp/对象文件之后。g++ <OPTIONS> <OBJECTS> <LIBRARIES>
,其中使用库B
中的符号的库A
应该出现在B
之后,即-lB -lA
,顺序对于ld
很重要。因为它将使用该库来解析当前丢失的符号,然后立即忘记该库曾经存在过。因此任何新发现的未解析符号都不会被解析。因此将库参数“右移”。2可以通过多次重复库来解决循环依赖。