linux下 c语言调用c++的静态库或动态库

c++ c++ 1910 人阅读 | 0 人回复

发表于 2023-2-23 15:23:30 | 显示全部楼层 |阅读模式

linux下 c语言调用c++的静态库或动态库。g++编译cpp 文件为库文件。编译C文件时gcc 要链接 -l stdc++ 这个库**(非常重要)
  1. //定义c++ class 头文件
  2. #ifndef REGEX_H
  3. #define REGEX_H

  4. class Regex
  5. {
  6. public:
  7.     Regex();
  8.     int add(int a,int b);
  9. };
  10. #endif // REGEX_H
复制代码
  1. // class 头文件
  2. #include "regex.h"

  3. Regex::Regex()
  4. {
  5. }

  6. int Regex::add(int a,int b){
  7.     return (a+b)*10;
  8. }
复制代码
  1. //test.h 文件
  2. //对c语言提供对外按c语言编译的接口

  3. #ifndef TEST_H
  4. #define TEST_H
  5. #ifdef __cplusplus
  6. extern "C" {
  7. #endif
  8. int test(int a,int b);

  9. #ifdef __cplusplus
  10. }
  11. #endif

  12. #endif // TEST_H
复制代码
  1. //test.cpp
  2. //对外接口实现  


  3. #include "test.h"
  4. #include"regex.h"
  5. #ifdef __cplusplus
  6. extern "C"{
  7. #endif

  8.     int test(int a,int b)
  9.     {
  10.         Regex regex;
  11.         return regex.add(a,b);
  12.     }

  13. #ifdef __cplusplus
  14. }
  15. #endif
复制代码
  1. //以上c++ 四个文件 编译成静态库或者动态库
  2. //gcc main.c -om -Iinclude -Laddr -llibname
  3. //C 语言测试文件

  4. #include<stdio.h>
  5. #include"./regex/test.h"

  6. int main(){

  7. int res=test(10,20);
  8. printf("res=%d\n",res);
  9. }
复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则