Reputation: 1017
I would like to use a C Library and a C++11 library in my application. It seems the usage of "complex" in the C and C++11 library conflicts, and it produces compilation error. A MWE is given here.
Contents of myLib_C.h:
#ifndef MYLIBC_H
#define MYLIBC_H
#include <math.h>
#include <complex.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef float complex cfloat;
typedef double complex cdouble;
#define myFunc_cfloat(r,i) ((float)(r) + ((float)(i))*I)
#define myFunc_cdouble(r,i) ((double)(r) + ((double)(i))*I)
#ifdef __cplusplus
} // extern "C"
#endif
#endif
The contents of myLib_CPP.h:
#ifndef MYLIBCPP_H
#define MYLIBCPP_H
#include "myLib_C.h" //uses myLib_C somewhere in this file
#include <iostream>
#include <complex>
inline void CppFunction()
{
std::cout<<"This file need to be compiled using C++11\n";
std::complex<float> a(10,100);
std::complex<float> b(1, 1);
auto c = a+b;
std::cout<<"c= "<<c<<std::endl;
}
#endif // MYLIBCPP_H
My main.cpp:
#include "myLib_C.h"
#include "myLib_CPP.h"
#include <iostream>
#include <complex>
int main()
{
std::cout<<"Hello World\n";
CppFunction();
return 0;
}
The contents of CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(myTest)
set(CMAKE_CXX_FLAGS "-std=c++11")
add_executable(myTest main.cpp)
When I compile, I get the following error:
error: expected initializer before ‘cfloat’
typedef float complex cfloat;
A similar problem was discussed in C Complex Numbers in C++?. The solution mentioned there is to replace complex
with _Complex
. This is not possible in my case as I will not be able to edit the C and C++ libraries.
Upvotes: 2
Views: 527
Reputation: 119857
extern "C" { ... }
doesn't magically turn C code inside braces into valid C++ code, so this is out.
Both language standards require their respective complex numbers to have the same layout as an array of two numbers of the corresponding floating-point type (i.e. both C++ std::complex<float>
and C float complex
behave just like float[2]
, layout-wise). You can exploit this. For example:
#ifdef __cplusplus
using cfloat = std::complex<float>;
#else
typedef float complex cfloat;
#endif
Now you can declare a cfloat
variable in one language and pass it to the other language, and this should work.
Upvotes: 6