【c++】C与C++的相互调用问题&opencv list not found

      在实际工作中可能经常要进行C和C++的混合编程,C++调用C语言的代码通常都比较容易,但也有一些细节需要注意。C要调用C++的代码就略为麻烦一些,因为C不支持面向对象的特征。


下面我们就来看看如何在C语言中使用C++的代码(包括C++类的方法)。为了简单起见,我将类的定义和实现放在一个文件中(通常应该是将分别放在.h和.cpp文件中)。自定义类文件(这里省略了头文件保护等其它细节)如下:
//* file TestClass.h */
 
class HJH
{
public:
    int add(int a, int b)
       {
              return (a + b);
       }
};
 
      将C++类封装为C函数的文件(为了简略也将声明和实现放在了同一个文件中)如下:
/* file TestCpp.cpp */
 
#include "TestClass.h"
 
extern "C" int add_cpp(int a, int b);
 
int add_cpp(int a, int b)
{
       HJH hjh;
 
       return hjh.add(a, b);      
}
 
      实际调用C++代码的C文件如下:
/*file TestC.c */
#include "stdio.h"
 
extern int add_cpp(int a, int b);
 
int main()
{
       printf("add_cpp = %d/n", add_cpp(2, 5));
      
       return 0;
}
上面的过程很清晰,就是用一个函数将C++类的使用封装起来,然后将它外部声明为C函数就可以了。
文件TestClass.h定义并实现了一个类,该类只有一个add方法。文件TestCpp.cpp定义并实现了一个函数add_cpp,函数中定义了一个HJH类对象并调用了该对象的add方法。然后将add_cpp函数进行外部声明为C。
TestC.c文件中为了使用add_cpp函数,也需要进行外部声明。这是为了通知编译器说明这个函数是在其他文件中实现(注意在C文件中的extern后面不可加”C”)。当这三个文件一起编译链接时,编译器就可以找到add_cpp的具体实现。

C中调用opencv c++接口时报错:list:No such file or directory
解决方法:opencvtest.h中添加opencv.hpp就会出错
//main.c
#include <stdio.h>
#include "opencvtest.h"

extern void opencv_function();

int main()
{
    printf("test c\n");

    opencv_function();
}
//opencvtest.h
#ifndef OPENCVTEST_H
#define OPENCVTEST_H


#endif // OPENCVTEST_H
//opencvtest.cpp
#include "opencvtest.h"
#include <iostream>

#include <opencv2/opencv.hpp>

using namespace cv;

extern "C" void opencv_function();

void opencv_function()
{
    Mat img = imread("1.bmp", 1);
    Mat img2;
    img2.create(10,10,CV_8UC1);//create test

    imshow("img", img);
    waitKey(0);
}

转自:http://blog.csdn.net/gobitan/article/details/1532769

猜你喜欢

转载自blog.csdn.net/qq_15947787/article/details/78785024
今日推荐