【问题标题】:Using C++11 and C libraries together for complex numbers将 C++11 和 C 库一起用于复数
【发布时间】: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


【解决方案1】:

extern "C" { ... } 不会神奇地将大括号内的 C 代码转换为有效的 C++ 代码,所以它已经过时了。

两种语言标准都要求它们各自的复数具有与对应浮点类型的两个数字的数组相同的布局(即 C++ std::complex&lt;float&gt; 和 C float complex 的行为就像 float[2],布局-明智的)。你可以利用这一点。例如:

#ifdef  __cplusplus
   using cfloat = std::complex<float>;
#else
   typedef float complex cfloat;
#endif

现在您可以用一种语言声明cfloat 变量并将其传递给另一种语言,这应该可以工作。

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 2017-03-20
    • 2015-11-28
    • 2013-12-22
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多