源代码是在没有正确#include的情况下编译的



我有一个非常简单的c++源,如下所示:

#include <iostream>
int main() {
srand(time(NULL));
}

我使用g++编译如下:

g++ ./test.cpp

但它成功地编译了,尽管time()函数是在ctime中定义的,并且它不包括在#include

我在大学的教授用visualstudio(vc++(运行代码,但如果不包括ctime,他就无法运行代码

我是不是遗漏了什么?

顺便说一下,我的g++版本是:

g++ (Ubuntu 11.2.0-7ubuntu2) 11.2.0

首先,在我的平台上,当我删除#include <iostream>时,它没有成功编译我使用的是WSL2 ubuntu 20.04,我使用的编译器是g++和clang++
无论是哪种编译器,都会给出错误:

>>> g++ t.cpp
t.cpp: In function ‘int main()’:
t.cpp:2:16: error: ‘NULL’ was not declared in this scope
2 |     srand(time(NULL));
|                ^~~~
t.cpp:1:1: note: ‘NULL’ is defined in header ‘<cstddef>’; did you forget to ‘#include <cstddef>’?
+++ |+#include <cstddef>
1 | int main() {
t.cpp:2:11: error: ‘time’ was not declared in this scope
2 |     srand(time(NULL));
|           ^~~~
t.cpp:2:5: error: ‘srand’ was not declared in this scope
2 |     srand(time(NULL));
|     ^~~~~
>>>clang t.cpp
t.cpp:2:16: error: use of undeclared identifier 'NULL'
srand(time(NULL));
^
1 error generated.

我认为您可以使用compile选项-E来提示编译器只进行预处理并查看预处理后的文件
如下:
g++ t.cpp -E -o pre_proccessed.cpp确定编译器是否在编译过程中做了你怀疑的事情;自动包括文件";

但是,当我添加#include <iostream>时它取得了成功
所以,我做了这个:

>>>g++ t.cpp -E  -o t_.cpp
>>>cat t_.cpp | grep srand
extern void srandom (unsigned int __seed) throw ();
extern int srandom_r (unsigned int __seed, struct random_data *__buf)
extern void srand (unsigned int __seed) throw ();
extern void srand48 (long int __seedval) throw ();
extern int srand48_r (long int __seedval, struct drand48_data *__buffer)
using ::srand;

这解释了为什么它的编译成功,因为这个平台中包含的iostream文件中有这个函数的定义。
此外,看看这个问题

事实上,stl可以相互包含
但是,即使在这个头文件中定义了它,您也不能依赖它,iostream实现的某些版本不包括它。

你应该做的是在使用srand时主动包含cstdlib文件,不要担心多重包含问题,std,stl本身可以很好地处理多重包含,现代编译器也可以很好的处理这个问题。

首先明确地包括您需要的东西,
(感谢darkblueflow的指出(
其次#include订单事项,

信不信由你,他们可以掩盖声明,如果第一种情况不起作用,就切换

#include <cstdlib>
#include <ctime>
// differs from
#include <ctime>
#include <cstdlib>
// in some aspects

你最好的办法是明确地包含标题记住这一点这祝好运

相关内容

最新更新