最近遇到一个问题, 下面来简化说下:
// int xxx(); int main() { xxx(); }
编译一下,自然编译不过, 信息为:
ubuntu@VM-0-15-ubuntu:~/taoge/cpp/test$ g++ -c main.cpp main.cpp: In function ‘int main()’: main.cpp:5:9: error: ‘xxx’ was not declared in this scope xxx(); ^ ubuntu@VM-0-15-ubuntu:~/taoge/cpp/test$
打开上述的注释, 得到:
int xxx(); int main() { xxx(); }
编译一下, 能通过吗? 看看:
ubuntu@VM-0-15-ubuntu:~/taoge/cpp/test$ g++ -c main.cpp ubuntu@VM-0-15-ubuntu:~/taoge/cpp/test$
链接一下, 发现xxx()未定义。
ubuntu@VM-0-15-ubuntu:~/taoge/cpp/test$ g++ main.o main.o: In function `main': main.cpp:(.text+0x5): undefined reference to `xxx()' collect2: error: ld returned 1 exit status
从而印证题目中的问题。
我当时的纳闷是, xxx函数没有定义, 居然能通过编译。 确实能。 要区分编译和链接所做的事。
再仔细看看上述的英文提示, 编译不通过, 显示的是not declared, 而链接不通过, 显示的是undefined. 所以, 一目了然了。