1. 程式人生 > 實用技巧 >c++全域性變數,uint8_t[]轉QString

c++全域性變數,uint8_t[]轉QString

extern

作用1:讓編譯器按C規則編譯函式名和變數名(保持名稱原樣,c++由於可以過載所以名稱前後會新增符號)
#ifdef __cplusplus
extern "C"
{
#endif

#ifdef __cplusplus
}
#endif
作用2:在標頭檔案中 extern int a; 宣告全域性變數或函式。其他編譯單元可以包含標頭檔案後定義或使用,在標頭檔案中最好不要寫成 extern int a = 1;

static

extern和static不能同時修飾一個變數,static聲明瞭全域性變數後,該變數同時也被定義了。static修飾的全域性變數的作用域只能是本身的編譯單元。
定義static全域性變數時,一般把它放在原檔案中而不是標頭檔案。
// test.h
#ifndef TEST1_H
#define TEST1_H
static char str[] = "123456";
void func1();
#endif

// test1.cpp
#include "test1.h"

void func1()
{
      str[0] = 'a';
      cout << str << endl;
}

// test2.cpp
#include "test.h"

void func2()
{
      cout << str << endl;
}

// main.cpp
int main()
{
      func1();  // "a23456"
      func2();  // "123456"  記憶體中存在兩份拷貝給兩個編譯單元使用

      return 0;
}

uint8_t[] 轉 QString

uint8_t DevName[32] = {0};
QString devNameStr = (char*)DevName;