攀升·Uranus


Something Different,Something New
数据加载中……

(转)C++程序调用C函数

转自:http://blog.csdn.net/ustcgy/archive/2009/12/23/5063082.aspx

这种需求很多,又因为C++和C是两种完全不同的编译链接处理方式,所以要稍加处理.总结大致有两大类实现方法.

文中给出的是完整的,具体的,但又最基本最简单的实现,至于理论性的东西在网上很容易搜索的到.

一.通过处理被调用的C头文件

a.h:

#ifndef __A_H
#define __A_H

#ifdef __cplusplus
extern "C" {
#endif

int ThisIsTest(int a, int b);

#ifdef __cplusplus
}
#endif

#endif

a.c:

#include "a.h"

int ThisIsTest(int a, int b) {
  return (a + b);
}

aa.h:

class AA {
  public:
      int bar(int a, int b);
};

aa.cpp:

#include "a.h"
#include "aa.h"
#include "stdio.h"

int AA::bar(int a, int b){
    printf("result=%d\n", ThisIsTest(a, b));
    return 0;
}

main.cpp:

#include "aa.h"

int main(int argc, char **argv){
  int a = 1;
  int b = 2;
  AA* aa = new AA();
  aa->bar(a, b);
  delete(aa);
  return(0);
}

Makefile:

all:
        gcc -Wall -c a.c -o a.o
        gcc -Wall -c aa.cpp -o aa.o
        gcc -Wall -c main.cpp -o main.o
        g++ -o test *.o

二. 通过处理调用的C++文件

恢复a.h文件为一般性C头文件,在aa.cpp文件中extern包含a.h头文件或函数.

a.h:

#ifndef __A_H
#define __A_H
int ThisIsTest(int a, int b);
#endif

aa.cpp:

extern "C"
{
    #include "a.h"
}
#include "aa.h"
#include "stdio.h"

int AA::bar(int a, int b){
    printf("result=%d\n", ThisIsTest(a, b));
    return 0;
}

or

aa.cpp:

#include "aa.h"
#include "stdio.h"

extern "C"
{
    int ThisIsTest(int a, int b);
}

int AA::bar(int a, int b){
    printf("result=%d\n", ThisIsTest(a, b));
    return 0;
}

posted on 2010-03-08 15:23 攀升 阅读(3005) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理