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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With