본문 바로가기

Linux

extern "C" gcc, g++ 라이브러리 컴파일

g++컴파일러를 사용해서 gcc로 컴파일된 라이브러리를 사용할 일이 생겼다.

gcc로 컴파일 된 라이브러리를 g++로 다시 컴파일 하기 어려웠기 때문이다.

그래서 여기저기 검색한 결과 아주 쉬운 방법이 있었다.


//현재 여기는 main.cpp파일

#include<iostream>

extern "C"

{

#include"Ccompiled.h"//C로 컴파일된 라이브러리의 헤더

}

int main()

{

    //cpp라이브러리를 사용하여 프로그래밍 한다~~

    return 0;

}


=========컴파일 과정=========

$g++ -o prog main.cpp -L. -lclibfile

 

gcc로 컴파일 된 라이브러리 이름은 libclibfile.a 라고 가정한다.

빨간 글씨로 된 extern "C" { } 의 방법을 사용하면 g++로 컴파일할 때 gcc로 컴파일 된 라이브러리를 사용가능하다.

 




How do I call a C function from C++?

Just declare the C function ``extern "C"'' (in your C++ code) and call it (from your C or C++ code). For example:

	// C++ code

	extern "C" void f(int);	// one way

	extern "C" {	// another way
		int g(double);
		double h();
	};

	void code(int i, double d)
	{
		f(i);
		int ii = g(d);
		double dd = h();
		// ...
	}

The definitions of the functions may look like this:

	/* C code: */

	void f(int i)
	{
		/* ... */
	}

	int g(double d)
	{
		/* ... */
	}

	double h()
	{
		/* ... */
	}

Note that C++ type rules, not C rules, are used. So you can't call function declared ``extern "C"'' with the wrong number of argument. For example:

	// C++ code

	void more_code(int i, double d)
	{
		double dd = h(i,d);	// error: unexpected arguments
		// ...
	}

How do I call a C++ function from C?

Just declare the C++ function ``extern "C"'' (in your C++ code) and call it (from your C or C++ code). For example:

	// C++ code:

	extern "C" void f(int);

	void f(int i)
	{
		// ...
	}

Now f() can be used like this:

	/* C code: */

	void f(int);
	
	void cc(int i)
	{
		f(i);
		/* ... */
	}

Naturally, this works only for non-member functions. If you want to call member functions (incl. virtual functions) from C, you need to provide a simple wrapper. For example:

	// C++ code:

	class C {
		// ...
		virtual double f(int);
	};

	extern "C" double call_C_f(C* p, int i)	// wrapper function
	{
		return p->f(i);
	}

Now C::f() can be used like this:

	/* C code: */

	double call_C_f(struct C* p, int i);
	
	void ccc(struct C* p, int i)
	{
		double d = call_C_f(p,i);
		/* ... */
	}

If you want to call overloaded functions from C, you must provide wrappers with distinct names for the C code to use. For example:

	// C++ code:

	void f(int);
	void f(double);

	extern "C" void f_i(int i) { f(i); }
	extern "C" void f_d(double d) { f(d); }

Now the f() functions can be used like this:

	/* C code: */

	void f_i(int);
	void f_d(double);
	
	void cccc(int i,double d)
	{
		f_i(i);
		f_d(d);
		/* ... */
	}

Note that these techniques can be used to call a C++ library from C code even if you cannot (or do not want to) modify the C++ headers.

[출처] http://www.research.att.com/~bs/bs_faq2.html#callCpp

'Linux' 카테고리의 다른 글

공유라이브러리-2  (0) 2008.09.05
공유 라이브러리-1  (0) 2008.09.05
library 만들기  (0) 2008.09.05
Windows 환경에서 Linux 환경으로 Library의 C++ 이식  (0) 2008.09.05
리눅스 gcc 컴파일러(c/c++)와 make 강좌  (0) 2008.09.04