[英]How to mimic the “multiple instances of global variables within the application” behaviour of a static library but using a DLL?
[英]How long live global variables in a static library?
假設我有以下靜態庫,用 C++ 實現:
int global = 0;
extern int foo(int i)
{
global += i;
return global;
}
我在我的項目中使用它如下:
#include <iostream>
extern int foo(int i);
int main()
{
std::cout << foo(1) << "\n";
std::cout << foo(1) << "\n";
std::cout << foo(1) << "\n";
}
此代碼打印出:
1
2
3
因此,顯然,全局變量“幸存”了函數調用,這與我在可執行文件中實現 foo 並多次調用該可執行文件不同,全局變量每次都將設置為零。
問題:全局變量在上面使用的靜態庫中存在多長時間? 只要調用可執行的main
函數即可? 甚至允許這樣做嗎?
您可以認為全局變量在進入main()
之前被初始化,並在main()
退出之后被銷毀。
實際的規則有點復雜,但在大多數像這樣的簡單情況下,它會涵蓋你。
在這種情況下,您所指的全局變量實際上是具有“全局作用域”的“靜態存儲持續時間對象”。
還有其他靜態存儲持續時間對象的示例。
extern int foo(int i)
{
static int global = 0; // marking this static inside a function
// makes it a static storage duration
// object that lives longer than the function.
global += i;
return global;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.