C++ 클래스에서 C 라이브러리를 사용하는 예제

개발 노트 2008. 7. 29. 08:53 posted by 무병장수권력자


C++ 클래스에서 C 라이브러리를 사용하는 예제

작성자 : 김문규
최초 작성일 : 2007. 3.23

오픈 소스 기반으로 작업을 할 때, 종종 C 라이브러리를 C++에서 링크(link)해야 할 경우가 있습니다. 이럴 때 막상하려 하면 난감할 때가 있지요? ^^; (저만 그런가 봅니다.)

예제를 통해 알아보도록 하겠습니다.

<foo.h>
#ifdef __cplusplus
extern "C" {
#endif

int foo(char *name);

#ifdef __cplusplus
}
#endif

 

<foo.c>
int foo(char *name)
{
        printf("%sn", name);
        return 1;
}

 

<bar.cpp>
#include <iostream>
#include "foo.h"
using namespace std;

int main()
{
        foo("hello");
        return 0;
}


이제
compile을 해 볼까요?

[root@superman test]$ gcc -c foo.c
[root@superman test]$ g++ -o main bar.cpp foo.o
[root@superman test]$ ./main
hello

성공하셨나요? ^^