【问题标题】:How to use C++ function from header in C?如何在 C 中使用标头中的 C++ 函数?
【发布时间】:2017-05-27 12:34:44
【问题描述】:

我正在写论文,但在 C 代码中使用 C++ 函数时遇到问题。我搜索了解决方案,发现了很多,但无论如何都没有用。请再给我解释一遍。

为了快点,我有类似下面的内容,在gcc main.c -o main 之后我得到undefined reference to 'cppfun'

cpp.h:

#pragma once

#ifdef __cplusplus
 extern "C" {
#endi

    void cppfun();

#ifdef __cplusplus
 }
#endif

cpp.cpp:

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

void cppfun()
{
    printf("cpp_fun");
}

ma​​in.c:

#include <stdio.h>
#indlude "cpp.h"

int main(int argc, char *argv[])
{
    cppfun();
    return 0;
}

【问题讨论】:

    标签: c++ c header main


    【解决方案1】:

    首先你通过-c编译器开关编译你的cpp代码无链接

    g++ cpp.cpp -c

    你有 cpp.o 文件,然后通过 gcc 编译并链接你的 main.c 与 cpp.h 和 cpp.o 文件

    gcc main.c -o main cpp.o

    我通过我的 linux 服务器测试了这个答案。这是工作。

    【讨论】:

      【解决方案2】:

      当您结合 C 和 C++ 时,您应该将包含 main 函数的翻译单元编译为 C++。不相反。这是a FAQ

      未定义的引用通常是因为您没有在缺少的东西所在的翻译单元中链接。您声明的构建命令是

      gcc main.c -o main
      

      虽然它应该是例如

      gcc -c main.c
      g++ -c cpp.cpp
      g++ cpp.o main.o -o main
      

      除上述外,主要翻译单元应为 C++。

      【讨论】:

        【解决方案3】:

        您需要在 main 之后包含所有 .cpp 文件。类似的东西:

        g++ main.cpp other.cpp etc.cpp -o main
        

        【讨论】:

        • 这也有效,我在 cpp 中有更多文件,这个命令可以完成所有工作,谢谢。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-18
        • 2010-09-22
        • 1970-01-01
        相关资源
        最近更新 更多