[英]can global variables be accessed and modified in various classes in C++
我遇到了代碼意粉,我需要在其中檢測流量控制,即一次發送一個數據。 我如何使用全局變量來解決這個問題? 如果全局變量不起作用,訪問和修改可能在不同類中的多個函數中的變量的方式是什么
我嘗試了以下操作(我正在粘貼部分代碼),但它給了我我無法解決的ld錯誤。 我想問一下解決這個問題的最佳方法。
文件1.h
int data_received; //global variable
class abc
{
.
.
.
public:
void send_data(..)
.
.
.
};
文件1.c
void send_data()
{
while(!end_of_file)
{
read_line;
data_received = 0;
transmit_data(line);
while(data_received == 0)
cout<<"waiting for response before proceeding\n";
}
}
文件2.c
//data receive class
void transmit_data()
{
....
....
....
//data sent upstream
data_received = 1;
}
我搜索了許多關於stackoverflow的帖子,但是沒有明確的答案。 有些人建議使用extern變量,但沒有明確的例子說明在多個類函數中修改外部變量。
您需要在頭文件中標記該extern
,然后在file1.c
或file2.c
對其進行一次定義。
例如
文件1.h
extern int data_received;
文件1.c
// initialize it
int data_received = 0;
文件2.c
// either do this if the include is logically needed
#include "file1.h"
// or
extern int data_received;
// then use it normally
void foo() {
cout << data_received << endl;
}
或者,如果這是C ++,則可以將該變量聲明為類中的static
變量,在.cpp
文件中對其進行定義,然后將其像普通變量一樣使用,但以該類的范圍解析為前綴。 例如
class Something {
public:
static int data_received = 0;
};
void foo() {
cout << Something::data_received << endl;
}
通過在頭文件中定義全局變量,您將在它包含的所有“ c”文件中創建它的副本。 到目前為止,ld將抱怨。 您需要在頭文件中將其聲明為“ extern”,然后在單個“ c”文件中對其進行定義。
file1.h
extern int data_received;
文件1.c
#include <file1.h>
int data_received = 0;
文件2.c
#include <file1.h>
這樣,您將只定義它的一個副本,並使所有包含頭文件的文件都知道它。
請進一步了解
Declare
與Define
。 compile
與link
define
全局變量
// file1.cpp
int data_received;
extern
告訴編譯器在鏈接器時可以找到data_received
。
// file2.cpp
extern int data_received;
另外, static
可以限制my_global_var
僅在定義它的文件中使用。 例
// file3.cpp
static int my_global_var = 1;
linker
中將發生錯誤
// file4.cpp
extern int my_global_var;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.