Friday, 23 June 2017

c++ - extern "C" causing an error "expected '(' before string constant"

Answer




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();
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...