例子如下:
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
unordered_map<string,double> coll { { "tim", 9.9 }, { "struppi", 11.77 }};
// square the value of each element:
for (pair<const string,double>& elem : coll) {
elem.second *= elem.second;
}
// print each element (key and value):
for (const auto& elem : coll) {
cout << elem.first << ": " << elem.second << endl;
}
}
执行:
gcc test.cpp -o test -lstdc++ -std=c++14
编译报如下错误!
/usr/bin/ld: /tmp/ccImiJor.o: undefined reference to symbol ‘ceil@@GLIBC_2.2.5’
//lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
报错说,未能识别ceil这个标识,虽然我们并没有显式调用ceil这个函数,但事实程序在编译时需要对**unordered_map<string,double> coll { { “tim”, 9.9 }, { “struppi”, 11.77 }};**调用这个函数。
gcc 编译时增加 -lm 选项,这样程序就能引用 libm.so(libmath) 库了。因为书序函数是位于libm.so 库文件中的,-lm 选项告诉编译器书序函数要到这个库文件中查找。
cmath是c++语言中的库函数,其中的c表示函数是来自c标准库的函数,math为数学常用库函数。编译时必须加上参数「-lm」(表示连结至数学函式库)。
再次执行:
gcc test.cpp -o test -lstdc++ -std=c++11 -lm
编译通过!!
总结下,对于这类错误,只需要依葫芦画瓢,找到对应的库标识,编译的时候加上就好了。
如果不想存在这种隐式的转换,可以按照下面的方式实现:
#include <unordered_map>
#include <string>
#include <iostream>
using namespace std;
int main()
{
unordered_map<string,double> coll;
coll.insert( { { "tim", 9.9 }, { "struppi", 11.77 } });
// square the value of each element:
for (pair<const string,double>& elem : coll) {
elem.second *= elem.second;
}
// print each element (key and value):
for (const auto& elem : coll) {
cout << elem.first << ": " << elem.second << endl;
}
}
执行如下编译通过:
gcc test.cpp -o test -lstdc++ -std=c++14