zoukankan      html  css  js  c++  java
  • C调用C++代码

    有时C程序里需要用到C++的类,但是C语言又不能直接调用类,这时需要把C++的类使用C接口封装后,再调用,

    可以将封装后的C++代码编译成库文件,供C语言调用;

    需要注意的是,封装的C++代码库文件是用g++编译的,所以在C中调用时,需要添加extern "C"{}关键字。

    编译c代码时,要加上-lstdc++

    如下代码,是c代码使用C++的map容器的例子:

    //test.cpp 封装C++代码
    
    
    #include <map>
    #include <iostream>
    #include "test.h"
    
    using namespace std;
    
    static map<int, int> m_testMap;
    
    
    void pushVal(int key, int val)
    {
    	m_testMap[key] = val;
    }
    
    
    int getVal(int key)
    {
    	map<int, int>::iterator iter = m_testMap.find(key);
    	if (iter != m_testMap.end() )
    	{
    		return iter->second;
    	}
    
    	return  -1;
    }
    
    //头文件 test.h
    
    #ifndef _TEST_H_
    #define _TEST_H_
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    void pushVal(int key, int val);
    int getVal(int key );
    
    
    #ifdef __cplusplus
    }
    #endif
    
    
    #endif
    

    main函数,调用封装的C++接口:

    //main.c
    
    #include <stdio.h>
    #include "test.h"
    
    
    
    int main()
    {
    	printf("test
    ");
    	for (int i = 0; i < 10; i++)
    	{
    		printf("push key: %d, val: %d
    ", i, i*10);
    		pushVal(i, i*10);
    	}
    	
    	int val = 0;
    	for (int i = 0; i < 10; i++)
    	{
    		val = getVal(i);
    		printf("get key: %d, val: %d
    ", i,val);
    	}
    	return 0;
    }
    

    编译的时候,为了简单,我这里没有编译成库文件,直接用引用.o编译的:

    makefile:

    all: 
    	g++ -Wall -c  test.cpp -o test.o
    	gcc -Wall -c  main.c -o main.o
    
    	gcc -Wall test.o main.o -o test -lstdc++
    
    clean:
    	rm test *.o
    

    编译运行结果如下:

    make
    g++ -Wall -c  test.cpp -o test.o
    gcc -Wall -c  main.c -o main.o
    gcc -Wall test.o main.o -o test -lstdc++
    
    运行:
    ./test
    test
    push key: 0, val: 0
    push key: 1, val: 10
    push key: 2, val: 20
    push key: 3, val: 30
    push key: 4, val: 40
    push key: 5, val: 50
    push key: 6, val: 60
    push key: 7, val: 70
    push key: 8, val: 80
    push key: 9, val: 90
    get key: 0, val: 0
    get key: 1, val: 10
    get key: 2, val: 20
    get key: 3, val: 30
    get key: 4, val: 40
    get key: 5, val: 50
    get key: 6, val: 60
    get key: 7, val: 70
    get key: 8, val: 80
    get key: 9, val: 90

    个人微信服务号同步推送文章(微信公众号:fensnote):

  • 相关阅读:
    EXE、DLL和OCX文件的最佳压缩工具ASPack
    mysql忘记帐号密码 解决办法。
    vs2010 C++ 静态编译(解决:程序在别人的机子运行不了,缺少mfc100.dll, xxx100d.dll等的解决方法)
    去掉word每个标题前都有个小黑点 附word2003与2007方法
    struts2 中jsp页面replace的使用
    struts2 改变portlet windowState
    .net 知识补充 注意点
    广义表(1)
    字符串匹配(kmp)
    二叉排序树
  • 原文地址:https://www.cnblogs.com/fensnote/p/13436502.html
Copyright © 2011-2022 走看看