C++とC変数または関数の混合呼び出し

3674 ワード

第一部:C++がC変数または関数を呼び出す
もし私がCファイルの中でいくつかの機能を実現したいならば、CPPファイルの中でこれらの機能に対する呼び出しを実現して、私はどのようにしますか?
プログラムを貼り付けてから分析します.
// file name : inct.h
#ifndef _INCT_H_
#define _INCT_H_

#define NUM 8

#ifdef __cplusplus
extern "C" {
#endif
// global C
extern int g_data[4][NUM];

// function

int* func(int n);

#ifdef __cplusplus
}
#endif

#endif
//file name : inct.c
#include "inct.h"
#include <stdlib.h>
#include <stdio.h>

int g_data[4][NUM]= \
{ \
  {  0, 0,   0, 64,  0,   0, 0,  0 },\
  { -1, 4, -10, 58, 17,  -5, 1,  0 },\
  { -1, 4, -11, 40, 40, -11, 4, -1 },\
  {  0, 1,  -5, 17, 58, -10, 4, -1 }\
};\

int* func(int n)
{
    printf("your input is %d.
", n); return (int*)malloc(n*sizeof(int)); }
// file name : test.cpp
#include <iostream>
#include <string>
#include <cstring>
#include "inct.h"
#include <stdlib.h>
#include <stdio.h>
using namespace std;

int main(int argc, char **argv)
{
    int n=NUM;
    int *data = func(n);
    for (int i = 0; i < n; i++)
    {
        data[i] = g_data[2][i];
        printf("data[%d]=%4d
", i, data[i]); } free(data); return 0; }

このようにコンパイルします.
1、まずinct.cコンパイル:
gcc -c -I. inct.c

このコンパイルはinctを出力します.o
実行過程分析:gccコンパイル時、予め定義されていない_cplusplusというマクロなのでextern「C」は有効ではありませんinct.hは一般的なCプログラムとしてコンパイルに成功した.
2、test.cppはC++コンパイラでコンパイル:
g++ -c -I. test.cpp

出力test.o
g++で定義されている_cplusplusだからtestcpp中対inct.h中のすべての機能参照にextern"C"が追加する、これにより、c++中のプログラム参照が追加される.hの中のものは、Cコンパイラによってコンパイルされたプログラムと見なされます.コンパイルも問題ありません.
3、すべてのコンパイル中間結果をリンクする
g++ test.o inct.o -o test

第2部:CでC++を呼び出す関数または変数
先にコードを貼り付けます.
inct.hの内容は変わっていません.
inct.cをinctに変更する.cpp、次のプログラムの内容を変更します.
//file name : inct.c
#include "inct.h"
#include <iostream>
using namespace std; //  std    

int g_data[4][NUM]= \
{ \
  {  0, 0,   0, 64,  0,   0, 0,  0 },\
  { -1, 4, -10, 58, 17,  -5, 1,  0 },\
  { -1, 4, -11, 40, 40, -11, 4, -1 },\
  {  0, 1,  -5, 17, 58, -10, 4, -1 }\
};\

int* func(int n)
{
    cout << "your input is " << n << endl; //   cout
    return (new int[n]); //    new
    //return (int*)malloc(n*sizeof(int));
}

test.cppをtestに変更する.c,内容変更:
// file name : test.c
#include "inct.h"
#include <stdlib.h> 
#include <stdio.h> //    C    

int main(int argc, char **argv)
{
    int n=NUM;
    int *data = func(n);
    int i; // i       ,C   
    for (i = 0; i < n; i++)
    {
        data[i] = g_data[2][i];
        printf("data[%d]=%4d
", i, data[i]); printf, C } free(data); // new free return 0; }

次のようにコンパイルします.
1、まずinct.cppコンパイル:
g++ -c -I. inct.cpp

このコンパイルはinctを出力します.o
実行過程分析:g++コンパイル時、予め定義されている_cplusplusというマクロなのでextern「C」は有効ですinct.hは一般的なC++プログラムとしてコンパイルに成功したが,コンパイル後の変数と関数はCまたはC++プログラムで使用できる.
2、test.c Cコンパイラでコンパイル:
gcc -c -I. test.c

出力test.o
gccでは定義されていません_cplusplusだからtestc中対inct.hのすべての機能参照にextern「C」が追加されていないため、C言語プログラムはこれらの関数または変数を正常に参照する.
特にextern「C」はC++にしかないので、Cではexternのみで、変数の前に変数の宣言を表し、変数の定義を表しません.
3、すべてのコンパイル中間結果をリンクする
g++ test.o inct.o -o test
または
gcc test.o inct.o -o test -lstdc++ 

これでまだ問題がありますか.