簡體   English   中英

我可以使用extern“ C” {c的頭文件}

[英]can I use extern “C” { headerfile of c }

不用在“ extern "C" {} ”中編寫每個函數,我可以在該塊中寫入整個頭文件。

extern "C"
{
  #include "myCfile.h" 
} 

我已經嘗試過了,但是它根本不起作用,為什么它不起作用? 如果我們必須在c ++項目中使用100個C函數,是否需要在extern塊中提供所有函數,還有其他簡單的方法嗎?

例如:

extern "C"
{
 void fun1();
 void fun2();
 void fun3();
 void fun4();
 void fun5();
 .
 .
 .
 .
 fun100();
}

還有沒有其他簡單的方法,例如extern "C" { myCfunctions.h } ???

#include僅在#include的位置包含指定的標頭。 它是否有效取決於"myCfile.h"包含的內容。 特別是,在這樣的上下文中包含任何標准庫頭都是無效的,並且很可能會破壞常用的實現。

通常的處理方法是使標頭本身可以安全地從C ++使用。 僅C的標頭可能包含

#ifndef H_MYCFILE
#define H_MYCFILE

#include <stddef.h>

void mycfunc1(void);
void mycfunc2(int i);
void mycfunc3(size_t s);

#endif

對此進行修改以使其可以從C ++安全使用:

#ifndef H_MYCFILE
#define H_MYCFILE

#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

void mycfunc1(void);
void mycfunc2(int i);
void mycfunc3(size_t s);

#ifdef __cplusplus
}
#endif

#endif

使用這樣的標頭,您將無法安全地將整個標頭放入extern "C"塊中。 但是,該標頭本身可以確保#include <stddef.h>放在一個extern "C"塊中,而仍將所有函數聲明放在一個單獨的extern "C"塊中,避免必須為每個塊重復它。

您做錯了。

因為

extern "C" { myCfunctions.h }

應該管用。 請參見下面的示例程序。


讓我們來看示例代碼。

ctest1.c

#include<stdio.h>

void ctest1(int *i)
{
   printf("This is from ctest1\n"); // output of this is missing
   *i=15;
   return;
}

ctest2.c

#include<stdio.h>

void ctest2(int *i)
{
   printf("This is from ctest2\n"); // output of this is missing
   *i=100;
   return;
}

ctest.h

void ctest1(int *);
void ctest2(int *);

現在讓我們從中制作c庫

gcc -Wall -c ctest1.c ctest2.c
ar -cvq libctest.a ctest1.o ctest2.o

現在,讓基於cpp的文件將使用此c apis prog.cpp

#include <iostream>
extern "C" {
#include"ctest.h"
}
using namespace std;

int main()
{
  int x;
  ctest1(&x);
  std::cout << "Value is" << x;
  ctest2(&x);
  std::cout << "Value is" << x;

}

現在讓我們用C庫編譯這個c ++程序

g++ prog.cpp libctest.a

輸出為: 值is15值is100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM