Fogeaters, Light The World.

07

2016-Feb

C++ 과 C 를 같은 프로젝트에서 사용하기

작성자: title: MoonBlonix IP ADRESS: *.148.87.98 조회 수: 1505

본문 시작전에...

C++ 프로젝트에 C 파일을 추가하고 싶은 경우 그냥 파일이름에 .c 를 .cpp 로 바꿔라 그게 편하다. 100% 호환된다.


출처 :: https://isocpp.org/wiki/faq/mixing-c-and-cpp


What do I need to know when mixing C and C++ code?  

Here are some high points (though some compiler-vendors might not require all these; check with your compiler-vendor’s documentation):

  • You must use your C++ compiler when compiling main() (e.g., for static initialization)
  • Your C++ compiler should direct the linking process (e.g., so it can get its special libraries)
  • Your C and C++ compilers probably need to come from the same vendor and have compatible versions (e.g., so they have the same calling conventions)

In addition, you’ll need to read the rest of this section to find out how to make your C functions callable by C++ and/or your C++ functions callable by C.

BTW there is another way to handle this whole thing: compile all your code (even your C-style code) using a C++ compiler. That pretty much eliminates the need to mix C and C++, plus it will cause you to be more careful (and possibly —hopefully!— discover some bugs) in your C-style code. The down-side is that you’ll need to update your C-style code in certain ways, basically because the C++ compiler is more careful/picky than your C compiler. The point is that the effort required to clean up your C-style code may be less than the effort required to mix C and C++, and as a bonus you get cleaned up C-style code. Obviously you don’t have much of a choice if you’re not able to alter your C-style code (e.g., if it’s from a third-party).

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:

  1. // C++ code
  2. extern "C" void f(int); // one way
  3. extern "C" { // another way
  4. int g(double);
  5. double h();
  6. };
  7. void code(int i, double d)
  8. {
  9. f(i);
  10. int ii = g(d);
  11. double dd = h();
  12. // ...
  13. }

The definitions of the functions may look like this:

  1. /* C code: */
  2. void f(int i)
  3. {
  4. /* ... */
  5. }
  6. int g(double d)
  7. {
  8. /* ... */
  9. }
  10. double h()
  11. {
  12. /* ... */
  13. }

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

  1. // C++ code
  2. void more_code(int i, double d)
  3. {
  4. double dd = h(i,d); // error: unexpected arguments
  5. // ...
  6. }

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:

  1. // C++ code:
  2. extern "C" void f(int);
  3. void f(int i)
  4. {
  5. // ...
  6. }

Now f() can be used like this:

  1. /* C code: */
  2. void f(int);
  3. void cc(int i)
  4. {
  5. f(i);
  6. /* ... */
  7. }

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:

  1. // C++ code:
  2. class C {
  3. // ...
  4. virtual double f(int);
  5. };
  6. extern "C" double call_C_f(C* p, int i) // wrapper function
  7. {
  8. return p->f(i);
  9. }

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

  1. /* C code: */
  2. double call_C_f(struct C* p, int i);
  3. void ccc(struct C* p, int i)
  4. {
  5. double d = call_C_f(p,i);
  6. /* ... */
  7. }

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

  1. // C++ code:
  2. void f(int);
  3. void f(double);
  4. extern "C" void f_i(int i) { f(i); }
  5. extern "C" void f_d(double d) { f(d); }

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

  1. /* C code: */
  2. void f_i(int);
  3. void f_d(double);
  4. void cccc(int i,double d)
  5. {
  6. f_i(i);
  7. f_d(d);
  8. /* ... */
  9. }

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.

How can I include a standard C header file in my C++ code?  

To #include a standard header file (such as <cstdio>), you don’t have to do anything unusual. E.g.,

  1. // This is C++ code
  2. #include <cstdio> // Nothing unusual in #include line
  3. int main()
  4. {
  5. std::printf("Hello world\n"); // Nothing unusual in the call either
  6. // ...
  7. }

If you think the std:: part of the std::printf() call is unusual, then the best thing to do is “get over it.” In other words, it’s the standard way to use names in the standard library, so you might as well start getting used to it now.

However if you are compiling C code using your C++ compiler, you don’t want to have to tweak all these calls from printf() to std::printf(). Fortunately in this case the C code will use the old-style header <stdio.h> rather than the new-style header <cstdio>, and the magic of namespaces will take care of everything else:

  1. /* This is C code that I'm compiling using a C++ compiler */
  2. #include <stdio.h> /* Nothing unusual in #include line */
  3. int main()
  4. {
  5. printf("Hello world\n"); /* Nothing unusual in the call either */
  6. // ...
  7. }

Final comment: if you have C headers that are not part of the standard library, we have somewhat different guidelines for you. There are two cases: either you can’t change the header, or you can change the header.

How can I include a non-system C header file in my C++ code?  

If you are including a C header file that isn’t provided by the system, you may need to wrap the #include line in an extern "C" { /*...*/ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.

  1. // This is C++ code
  2. extern "C" {
  3. // Get declaration for f(int i, char c, float x)
  4. #include "my-C-code.h"
  5. }
  6. int main()
  7. {
  8. f(7, 'x', 3.14); // Note: nothing unusual in the call
  9. // ...
  10. }

Note: Somewhat different guidelines apply for C headers provided by the system (such as <cstdio>) and for C headers that you can change.

How can I modify my own C header files so it’s easier to #include them in C++ code?  

If you are including a C header file that isn’t provided by the system, and if you are able to change the C header, you should strongly consider adding the extern "C" {...} logic inside the header to make it easier for C++ users to #include it into their C++ code. Since a C compiler won’t understand the extern "C" construct, you must wrap the extern "C" { and } lines in an #ifdef so they won’t be seen by normal C compilers.

Step #1: Put the following lines at the very top of your C header file (note: the symbol __cplusplus is #defined if/only-if the compiler is a C++ compiler):

  1. #ifdef __cplusplus
  2. extern "C" {
  3. #endif

Step #2: Put the following lines at the very bottom of your C header file:

  1. #ifdef __cplusplus
  2. }
  3. #endif

Now you can #include your C header without any extern "C" nonsense in your C++ code:

  1. // This is C++ code
  2. // Get declaration for f(int i, char c, float x)
  3. #include "my-C-code.h" // Note: nothing unusual in #include line
  4. int main()
  5. {
  6. f(7, 'x', 3.14); // Note: nothing unusual in the call
  7. // ...
  8. }

Note: Somewhat different guidelines apply for C headers provided by the system (such as <cstdio>) and for C headers that you can’t change.

Note: #define macros are evil in 4 different ways: evil#1evil#2evil#3, and evil#4. But they’re still useful sometimes. Just wash your hands after using them.

How can I call a non-system C function f(int,char,float) from my C++ code?  

If you have an individual C function that you want to call, and for some reason you don’t have or don’t want to #include a C header file in which that function is declared, you can declare the individual C function in your C++ code using the extern "C" syntax. Naturally you need to use the full function prototype:

  1. extern "C" void f(int i, char c, float x);

A block of several C functions can be grouped via braces:

  1. extern "C" {
  2. void f(int i, char c, float x);
  3. int g(char* s, const char* s2);
  4. double sqrtOfSumOfSquares(double a, double b);
  5. }

After this you simply call the function just as if it were a C++ function:

  1. int main()
  2. {
  3. f(7, 'x', 3.14); // Note: nothing unusual in the call
  4. // ...
  5. }

How can I create a C++ function f(int,char,float) that is callable by my C code?  

The C++ compiler must know that f(int,char,float) is to be called by a C compiler using the extern "C" construct:

  1. // This is C++ code
  2. // Declare f(int,char,float) using extern "C":
  3. extern "C" void f(int i, char c, float x);
  4. // ...
  5. // Define f(int,char,float) in some C++ module:
  6. void f(int i, char c, float x)
  7. {
  8. // ...
  9. }

The extern "C" line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling (e.g., preceded by a single underscore). Since name overloading isn’t supported by C, you can’t make several overloaded functions simultaneously callable by a C program.

If you didn’t get your extern "C" right, you’ll sometimes get linker errors rather than compiler errors. This is due to the fact that C++ compilers usually “mangle” function names (e.g., to support function overloading) differently than C compilers.

See the previous two FAQs on how to use extern "C".

How can I pass an object of a C++ class to/from a C function?  

Here’s an example (for info on extern "C", see the previous two FAQs).

Fred.h:

  1. /* This header can be read by both C and C++ compilers */
  2. #ifndef FRED_H
  3. #define FRED_H
  4. #ifdef __cplusplus
  5. class Fred {
  6. public:
  7. Fred();
  8. void wilma(int);
  9. private:
  10. int a_;
  11. };
  12. #else
  13. typedef
  14. struct Fred
  15. Fred;
  16. #endif
  17. #ifdef __cplusplus
  18. extern "C" {
  19. #endif
  20. #if defined(__STDC__) || defined(__cplusplus)
  21. extern void c_function(Fred*); /* ANSI C prototypes */
  22. extern Fred* cplusplus_callback_function(Fred*);
  23. #else
  24. extern void c_function(); /* K&R style */
  25. extern Fred* cplusplus_callback_function();
  26. #endif
  27. #ifdef __cplusplus
  28. }
  29. #endif
  30. #endif /*FRED_H*/

Fred.cpp:

  1. // This is C++ code
  2. #include "Fred.h"
  3. Fred::Fred() : a_(0) { }
  4. void Fred::wilma(int a) { }
  5. Fred* cplusplus_callback_function(Fred* fred)
  6. {
  7. fred->wilma(123);
  8. return fred;
  9. }

main.cpp:

  1. // This is C++ code
  2. #include "Fred.h"
  3. int main()
  4. {
  5. Fred fred;
  6. c_function(&fred);
  7. // ...
  8. }

c-function.c:

  1. /* This is C code */
  2. #include "Fred.h"
  3. void c_function(Fred* fred)
  4. {
  5. cplusplus_callback_function(fred);
  6. }

Unlike your C++ code, your C code will not be able to tell that two pointers point at the same object unless the pointers are exactly the same type. For example, in C++ it is easy to check if a Derived*called dp points to the same object as is pointed to by a Base* called bp: just say if (dp == bp) .... The C++ compiler automatically converts both pointers to the same type, in this case to Base*, then compares them. Depending on the C++ compiler’s implementation details, this conversion sometimes changes the bits of a pointer’s value.

(Technical aside: Most C++ compilers use a binary object layout that causes this conversion to happen with multiple inheritance and/or virtual inheritance. However the C++ language does not impose that object layout so in principle a conversion could also happen even with non-virtual single inheritance.)

The point is simple: your C compiler will not know how to do that pointer conversion, so the conversion from Derived* to Base*, for example, must take place in code compiled with a C++ compiler, not in code compiled with a C compiler.

NOTE: you must be especially careful when converting both to void* since that conversion will not allow either the C or C++ compiler to do the proper pointer adjustments! The comparison (x == y)might be false even if (b == d) is true:

  1. void f(Base* b, Derived* d)
  2. {
  3. if (b == d) { Validly compares a Base* to a Derived*
  4. // ...
  5. }
  6. void* x = b;
  7. void* y = d;
  8. if (x == y) { BAD FORM! DO NOT DO THIS!
  9. // ...
  10. }
  11. }

As stated above, the above pointer conversions will typically happen with multiple and/or virtual inheritance, but please do not look at that as an exhaustive list of the only times when the pointer conversions will happen.

You have been warned.

If you really want to use void* pointers, here is the safe way to do it:

  1. void f(Base* b, Derived* d)
  2. {
  3. void* x = b;
  4. void* y = static_cast<Base*>(d); // If conversion is needed, it will happen in the static_cast<>
  5. if (x == y) { // ☺ Validly compares a Base* to a Derived*
  6. // ...
  7. }
  8. }

Can my C function directly access data in an object of a C++ class 

Sometimes.

(For basic info on passing C++ objects to/from C functions, read the previous FAQ).

You can safely access a C++ object’s data from a C function if the C++ class:

  • Has no virtual functions (including inherited virtual functions)
  • Has all its data in the same access-level section (private/protected/public)
  • Has no fully-contained subobjects with virtual functions

If the C++ class has any base classes at all (or if any fully contained subobjects have base classes), accessing the data will technically be non-portable, since class layout under inheritance isn’t imposed by the language. However in practice, all C++ compilers do it the same way: the base class object appears first (in left-to-right order in the event of multiple inheritance), and member objects follow.

Furthermore, if the class (or any base class) contains any virtual functions, almost all C++ compliers put a void* into the object either at the location of the first virtual function or at the very beginning of the object. Again, this is not required by the language, but it is the way “everyone” does it.

If the class has any virtual base classes, it is even more complicated and less portable. One common implementation technique is for objects to contain an object of the virtual base class (V) last (regardless of where V shows up as a virtual base class in the inheritance hierarchy). The rest of the object’s parts appear in the normal order. Every derived class that has V as a virtual base class actually has a pointer to the V part of the final object.

Why do I feel like I’m “further from the machine” in C++ as opposed to C?  

Because you are.

As an OO programming language, C++ allows you to model the problem domain itself, which allows you to program in the language of the problem domain rather than in the language of the solution domain.

One of C’s great strengths is the fact that it has “no hidden mechanism”: what you see is what you get. You can read a C program and “see” every clock cycle. This is not the case in C++; old line C programmers (such as many of us once were) are often ambivalent (can you say, “hostile”?) about this feature. However after they’ve made the transition to OO thinking, they often realize that although C++ hides some mechanism from the programmer, it also provides a level of abstraction and economy of expression which lowers maintenance costs without destroying run-time performance.

Naturally you can write bad code in any language; C++ doesn’t guarantee any particular level of quality, reusability, abstraction, or any other measure of “goodness.”

C++ doesn’t try to make it impossible for bad programmers to write bad programs; it enables reasonable developers to create superior software.

profile
List of Articles
번호 제목 글쓴이 날짜 조회 수
공지 [Web] 클라우드 IDE + 2 title: MoonBlonix 2017-06-25 15127
32 [AVR] HC_SR04 초음파센서 사용 file title: MoonBlonix 2016-02-13 1669
31 [AVR] 피에조 부저 활용 file + 1 title: MoonBlonix 2016-02-12 1956
30 칼만필터(Kalman Filter) + 2 title: MoonBlonix 2016-02-11 4377
29 low pass filter, high pass filter (저역통과필터, 고역통과필터) file title: MoonBlonix 2016-02-11 1455
28 [AVR] 루프 실행시간 측정 (아두이노의 Millis(), Micros() 분석) title: MoonBlonix 2016-02-09 1456
27 상보필터(Complementary Filter) file title: MoonBlonix 2016-02-09 1739
26 가속도, 자이로 센서에 대해 title: MoonBlonix 2016-02-09 1572
25 [AVR] UART 통신 file title: MoonBlonix 2016-02-07 1608
» C++ 과 C 를 같은 프로젝트에서 사용하기 title: MoonBlonix 2016-02-07 1505
23 라즈베리파이 운영체제에 관하여 title: MoonBlonix 2016-02-05 1459
22 [리눅스] 기본 명령어 title: MoonBlonix 2016-02-05 1632
21 [리눅스] C 언어 개발환경 구축 title: MoonBlonix 2016-02-05 1863
20 라즈베리파이 GPIO 핀 배열 file title: MoonBlonix 2016-02-05 2059
19 C++ 멤버 함수 포인터 title: MoonBlonix 2016-01-23 1775
18 AVR 직접만든 DC모터 라이브러리 (C++ Class) file title: MoonBlonix 2016-01-16 1517
17 [AVR] I/O 포트 메뉴얼 (ATMega128) file title: MoonBlonix 2016-01-16 1592
16 AVR delay 함수 (_delay_ms, _delay_us) title: MoonBlonix 2016-01-15 1640
15 AVR 멀티채널 PWM (타이머 하나로 여러 PWM 구동) title: MoonBlonix 2016-01-15 1651
14 AVR 초패스트 PWM title: MoonBlonix 2016-01-14 1565
13 AVR 타이머 응용 여러 PWM 방식과 예제 file + 1 title: MoonBlonix 2016-01-14 1651