【发布时间】:2020-09-07 18:15:27
【问题描述】:
我想在我的应用程序中使用 C 库和 C++11 库。似乎 C 和 C++11 库中“复杂”的使用存在冲突,并且会产生编译错误。 此处给出了 MWE。
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
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
我的 main.cpp:
#include "myLib_C.h"
#include "myLib_CPP.h"
#include <iostream>
#include <complex>
int main()
{
std::cout<<"Hello World\n";
CppFunction();
return 0;
}
CMakeLists.txt的内容:
cmake_minimum_required(VERSION 3.10)
project(myTest)
set(CMAKE_CXX_FLAGS "-std=c++11")
add_executable(myTest main.cpp)
编译时出现以下错误:
error: expected initializer before ‘cfloat’
typedef float complex cfloat;
C Complex Numbers in C++? 中讨论了类似的问题。提到的解决方案是将complex 替换为_Complex。在我的情况下这是不可能的,因为我将无法编辑 C 和 C++ 库。
【问题讨论】:
-
typedef float complex cfloat;不是有效的 C++ 代码,无论是否被extern "C"包围。您不能在任何 C++ 源文件中使用该 C 语法。为什么你认为你需要?显示的代码无缘无故包含myLib_C.h- 您不要尝试使用其中的任何内容。 -
extern "C" 以相反的方式使用。每当用户想在 C 中使用 C++ 函数时,您将它们包装在 extern "C" 中。 C++ 以这种方式不会破坏支持函数重载所需的函数名称。
标签: c c++11 compiler-errors