6

file1.c

int add(int a, int b) { return (a+b); } 

file2.cpp

void main() { int c; c = add(1,2); } 

h1.h

extern "C" { #include "stdio.h" int add(int a,int b); } 

Case 1: when i include h1.h in file1.c file then gcc compiler throw an error "expected '(' before string constant".

case 2: when I include h1.h in file2.cpp file compilation work successfully

Question:

1) Does it mean that I can not include header file in C with extern "C" function in it??

2) Can I include header within extern"C" like shown below

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

3) Can I put c++ functions definitions in header file with extern "C" so that i can call it in C file?

for example

a.cpp ( cpp file)

void test() { std::printf("this is a test function"); } 

a.h (header file)

extern "C" { void test(); } 

b_c.c ( c file)

#include "a.h" void main() { test(); } 
2

2 Answers 2

12

Write a.h like this:

#pragma once #ifdef __cplusplus extern "C" { #endif int add(int a,int b); #ifdef __cplusplus } #endif 

This way you can declare multiple functions - there is no need to prefix each one with extern C. As others mentioned: extern C is a C++ thing, so it needs to "disappear" when seen by C compiler.

Sign up to request clarification or add additional context in comments.

Comments

2

Since extern "C" is not understood by a C-compiler you need to create a header that can both be included in a C and C++ file.

E.g.

#ifdef __cplusplus extern "C" int foo(int,int); #else int foo(int,int); #endif 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.