C++ 動態庫的全局變量和函數中定義的靜態變量

本文主要驗證動態庫的全局變量和動態變量影響環境,經測試驗證。動態庫,代碼共享,數據分離,不管是什麼數據。

Compute.h:代碼如下:

#ifndef __COMPUTE_H
#define __COMPUTE_H

int GetResult();
int GetStaticResult();

#endif

 

Compute.cpp:代碼如下:

#include "Compute.h"

static int gn_test = 1;
int GetResult(){
    ++gn_test;

    return gn_test;
}

int GetStaticResult(){
    static int s_nTest = 1;
    ++s_nTest;

    return s_nTest;
}

 

main.cpp代碼如下:

#include "Compute.h"

#include <iostream>
#include <thread>
#include <chrono>

void ShowValue(){
    while(true){
        std::this_thread::sleep_for(std::chrono::seconds(2));
        std::cout << "Value:" << GetResult() << std::endl;
        std::cout << "Static value:" << GetStaticResult() << std::endl;
    }
}

int main(int argc, char**argv){
    std::thread tTask(ShowValue);

    tTask.join();

    return 0;
}

編譯選項如下:

     1、先生成動態庫:

g++ -fPIC -shared -o libCompute.so Compute.cpp

    2、生成執行文件,並鏈接動態庫

            g++ main.cpp -lpthread -L . -lCompute -o test

    3、拷貝文件到搜索目錄

     $ sudo cp libCompute.so /usr/lib/

    4、在2個終端運行,結果互不影響:

   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章