mac下通过gcc命令手动编译动态链接库示例
生活随笔
收集整理的這篇文章主要介紹了
mac下通过gcc命令手动编译动态链接库示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? 編譯動態鏈接庫,windows,linux,mac平臺各不相同,從文件上來說,windows下是dll,linux下是so,mac下是dylib;命令上也會有區別,windows下用cl,linux下用gcc但是參數是-fPIC -shared,而在mac下則是gcc -dynamiclib -o libxxx.dylib xxx.c。
? ? 這里介紹在mac下手動編譯動態庫示例:
? ? 準備hello.h
#ifndef SO_H #define SO_H int add(int a,int b); void hello(char* str,char* res); #endif? ? hello.c
#include <string.h> #include "hello.h" int add(int a,int b){return a + b + 1; } void hello(char* str,char* res){strcat(str,"world.");strcpy(res,str); }? ? 開始編譯動態庫:
gcc -dynamiclib -o libhello.dylib hello.c? ? 編譯完成,在目錄下會生成一個文件libhello.dylib
? ? 編寫測試程序,調用動態鏈接庫:
? ? test.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "hello.h" int main(){int sum = add(2,3);printf("sum=%d\n",sum);char str[] = "hello,";char res[20];hello(str,res);printf("hello()->%s\n",res);return 0; }? ? 首先需要編譯程序,生成可執行程序:
gcc test.c -lhello -L. -o test? ? 編譯不報錯,會生成test可執行程序,該程序可以直接運行:
admin@localhost:~/workspace/myapp2/dllapp$ ./test sum=6 hello()->hello,world.?
總結
以上是生活随笔為你收集整理的mac下通过gcc命令手动编译动态链接库示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单片机初学者,都会遇到的10个问题
- 下一篇: OpenCvSharp 图像缩放