简体   繁体   中英

compiling c and c++ files using g++

I am trying to compile a C and C++ file and link them together. I am following the answers from this link - Compiling C and C++ files together using GCC

However I have a different problem, which is not explained in that post. I have defined my main() in the C++ file and using a function whose details are there in the C file. The declaration of the function is there in a .h file, which is included both in the C and C++ file.

My C++ file -

#include<iostream>
#include<testc.h>

using namespace std;

extern "C" void cfunc(int, int);

int main()
{
    cout<<"Hello from cpp"<<endl;
    cfunc(3,6);
}

My C file -

#include<stdio.h>
#include<testc.h>

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

void cfunc(int a, int b)
{
    printf("Hello from c %d\n",cfunc2(a,b));
}

My .h file -

int cfunc2(int, int);
void cfunc(int, int);

As per other posts if I use a C function in my C++ code, I need to give the following definition in my C++ file -

extern "C" void cfunc(int, int);

However when I run like this I get the following error -

testcpp.cpp:6:17:  error: conflicting declaration of ‘void cfunc(int, int)’ with ‘C’ linkage
extern "C" void cfunc(int, int);

In file included from testcpp.cpp:2:0:
inc/testc.h:9:6: note: previous declaration with ‘C++’ linkage
void cfunc(int, int);

testcpp.cpp is where I make the call from main, testc.c contains the function definition and testc.h is the header file.

I run the following set of commands -

gcc -c -std=c99 -o testc.o testc.c -Iinc
g++ -c -std=c++0x -o testcpp.o testcpp.cpp -Iinc
g++ -o myapp testc.o testcpp.o

The inc folder contains the .h file

Anything I am doing wrong?

You do not need to provide another declaration of the function in the C++ file after you declared it in the .h file (and included this file from the C++, as it appears). This is what the C++ compiler clearly complains about, as they are different.

Instead, either wrap you declaration inside the .h file like the following:

 #ifdef __cplusplus
 extern "C" {
 #endif

 < your declarations go here >

 #ifdef __cplusplus
 }
 #endif

OR wrap the #include line in the same way in the .cpp file:

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

The idea is that the C and C++ parts will need to see the same function declared in a different way. That's why #ifdef is needed inside the .h file, as it is included from both C and C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM