mac下通过gcc命令手动编译动态链接库示例

2023-05-16

    编译动态链接库,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.

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mac下通过gcc命令手动编译动态链接库示例 的相关文章

随机推荐