我有一個非常簡單的 C 源代碼,如下所示:
#include <iostream>
int main() {
srand(time(NULL));
}
我正在使用 g 進行編譯:
g ./test.cpp
但它成功編譯,盡管time()函式是在ctime其中定義的并且不包含在#include
我的大學教授使用 Visual Studio (vc ) 運行代碼,但他無法在不包含的情況下運行代碼 ctime
我在這里錯過了什么嗎?
順便說一下,我的 g 版本是:
g (Ubuntu 11.2.0-7ubuntu2) 11.2.0
uj5u.com熱心網友回復:
首先,在我的平臺上,當我洗掉
我使用 WSL2 ubuntu 20.04,編譯器我使用 g 和 clang 時,它沒有成功#include <iostream>編譯。
無論是哪種編譯器,它都會給出錯誤:
>>> 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.
我認為您可以使用編譯選項 -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 實作不包含這個。
uj5u.com熱心網友回復:
給你的程式足夠的頭檔案是必要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/380353.html
上一篇:deque.at無加工函式
