g++編譯生成動態庫並使用


windows版本

一、生成dll

1、新建源文件

myfunction.h

#ifndef MYFUNCTION_H
#define MYFUNCTION_H
#include <iostream>

class Myfunction
{
public:
    Myfunction();
    static void log(char info);
};

#endif // MYFUNCTION_H

myfunction.cpp

#include "myfunction.h"

Myfunction::Myfunction()
{

}

void Myfunction::log(char info)
{
    std::cout << info;
}

2、編譯

打開cmd,執行

g++ myfunction.cpp -I D:\work\CppSpace\Testdll  -shared -o myfunction.dll

-I D:\work\CppSpace\Testdll 如果不填則默認在當前路徑查找依賴頭文件

 是否需要使用-fPIC?暫未接觸

3、生成dll

 

二、使用dll

1、將生成的myfunction.dll和myfunction.h放在獨立文件夾里

2、新建main.cpp

#include <iostream>
#include "myfunction.h"
int main(int argc, char *argv[])
{
    std::cout << "main:" << std::endl;

    Myfunction::log('c');
    getchar();
    return 0;
}

3、編譯

打開cmd,輸入

g++ myfunction.dll main.cpp -o my.exe

即可生成my.exe

4、雙擊exe測試

 

 

 

linux版本

待學習

 

 

 

 

Ps:動態庫也叫共享庫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM