2

I need to call "C" function which is having one argument variable "struct" (which is defined in "C" file), from "C++" file.

I used 'extern "C"', but getting linking error.

Please suggest me some way to do it ?

Thanks Priyanshu

5
  • Can you post what you have tried thus far? Commented Sep 6, 2010 at 8:56
  • "extern C" should be used in CPP file which declaring that function Commented Sep 6, 2010 at 8:59
  • @Alexander Rafferty: No, it's not. C++ is mostly a superset of C, but it is not a strict superset. (As a trivial example, a C program that uses variable names that conflict with C++-specific keywords obviously is not legal C++ code.) And that doesn't say much about linking compatibilities anyway. Commented Sep 6, 2010 at 9:49
  • @Alexander Rafferty: If you mean most of the language, okay. If you mean most C source files, I disagree. Well-written C code often is not valid C++. For example, in C it's usually recommended not to cast the return value of malloc, but C++ disallows implicit casts from void*. Commented Sep 6, 2010 at 17:31
  • Yes, I did mean most of the language. Most C can be modified to fit C++ standards, unless there is far to much source code to rake through. Commented Sep 6, 2010 at 23:03

2 Answers 2

4

Since you have not come back, here is a possible file arrangement and header file you probably should be looking at.

// Here is Header file (myh.h)

struct S{};

#ifdef __cplusplus
extern "C" {
#endif

void fn(S s);

#ifdef __cplusplus
}
#endif

// Here is CPP file (ZCPP.cpp)

#include "myh.h"

int main(){
   S s;
   fn(s);
}

// Here is C file (ZC.c)

#include <stdio.h>
#include "myh.h"

void fn(S s){
   printf("Hi\n");
}

[prompt@test ~]$ g++ zcpp.cpp zc.c

[prompt@test ~]$ ./a.out

Hi

[prompt@test ~]$

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

Comments

0

You should read this thread How to mix C and C++ for understanding the ins and outs of mixing C and C++ code.

When done, you can also have a look at the corresponding FQA thread.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.