如何在 C 中使用 header 中的 C++ 函数?
How to use C++ function from header in C?
我正在写论文,但在 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");
}
main.c:
#include <stdio.h>
#indlude "cpp.h"
int main(int argc, char *argv[])
{
cppfun();
return 0;
}
您需要在 main 之后包含所有 .cpp 文件。类似的东西:
g++ main.cpp other.cpp etc.cpp -o main
结合使用 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++。
首先你编译你的cpp代码没有link通过-c编译器开关
g++ cpp.cpp -c
并且您有 cpp.o 文件,然后通过 gcc
编译 link 您的 main.c 与 cpp.h 和 cpp.o 文件
gcc main.c -o main cpp.o
我通过 linux 服务器测试了这个答案。这是工作。
我正在写论文,但在 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");
}
main.c:
#include <stdio.h>
#indlude "cpp.h"
int main(int argc, char *argv[])
{
cppfun();
return 0;
}
您需要在 main 之后包含所有 .cpp 文件。类似的东西:
g++ main.cpp other.cpp etc.cpp -o main
结合使用 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++。
首先你编译你的cpp代码没有link通过-c编译器开关
g++ cpp.cpp -c
并且您有 cpp.o 文件,然后通过 gcc
编译 link 您的 main.c 与 cpp.h 和 cpp.o 文件gcc main.c -o main cpp.o
我通过 linux 服务器测试了这个答案。这是工作。