我经常看到程序编码如下:
extern "C" bool doSomeWork() {
//
return true;
}
Run Code Online (Sandbox Code Playgroud)
为什么我们使用extern "C"块?我们可以用C++中的东西替换它吗?使用有什么好处extern "C"吗?
我确实看到了一个解释这个的链接但是为什么我们需要在已经有C++的情况下用C语言编译?
在C++项目中,由于C和C++之间的标准不同,包括C源文件的.h文件会导致许多错误.
如何在C++项目(或main.cpp)中使用C源文件?
我是否需要一个extern "C" {}块来在C++程序中包含标准C头.只考虑在C++中没有对应项的标准C头.
例如:
extern "C" {
#include <fcntl.h>
#include <unistd.h>
}
Run Code Online (Sandbox Code Playgroud) 只是好奇.这显然不是一个非常好的实际编程解决方案,但是我想在Bless(十六进制编辑器)中创建一个可执行文件.
我的架构是x86.我能制作一个非常简单的程序是什么?你好世界?无限循环?与此问题类似,但在Linux中.
我正在用CMake构建C++应用程序.但它在C中使用了一些源文件.这是简化的结构:
主干/的CMakeLists.txt:
project(myapp)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -g -Wall")
add_subdirectory (src myapp)
Run Code Online (Sandbox Code Playgroud)
主干/ src目录/ main.cpp中:
#include "smth/f.h"
int main() { f(); }
Run Code Online (Sandbox Code Playgroud)
主干/ src目录/的CMakeLists.txt:
add_subdirectory (smth)
link_directories (smth)
set(APP_SRC main)
add_executable (myapp ${APP_SRC})
target_link_libraries (myapp smth)
Run Code Online (Sandbox Code Playgroud)
主干/ src目录/水木清华/ FH:
#ifndef F_H
#define F_H
void f();
#endif
Run Code Online (Sandbox Code Playgroud)
主干/ src目录/水木清华/ FC:
#include "f.h"
void f() {}
Run Code Online (Sandbox Code Playgroud)
躯干/ SRC /不便/的CMakeLists.txt
set (SMTH_SRC some_cpp_file1 some_cpp_file2 f)
add_library (smth STATIC ${SMTH_SRC})
Run Code Online (Sandbox Code Playgroud)
问题是:我运行gmake,它编译所有文件,当它将所有库连接在一起时,我得到:
undefined reference to `f()` in main.cpp
Run Code Online (Sandbox Code Playgroud)
如果我将fc重命名为f.cpp,一切都会好起来的.有什么区别以及如何处理它?
谢谢
我只是想进一步了解extern C函数.
根据我的知识,extern C函数始终是您正在尝试从已编译的应用程序调用的函数.可执行文件,静态库或动态库.
extern "C"
{
HRESULT CreateDevice();
typedef HRESULT (*CREATEDEVICE)();
HRESULT ReleaseDevice();
typedef HRESULT (*RELEASEDEVICE)();
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是......
我的理解是否正确?
它总是必须是一个C函数指针??'
为什么必须为每个函数使用typedef?
我假设你使用GetProcAddress().您正在为特定应用程序HEAP分配内存,而不是您从中调用它的内存.因此你必须从那个堆中释放它?
我试图在c ++程序中使用SQLite.我对C/C++的了解有限,因为我在这一点上主要使用Java.我在大学里上了一些课程,但已经有一段时间了,我们从未涉及过这样的课程.SQLite是用C语言编写的.在编译程序时你会怎么做?(我在我的Windows平台上安装了MinGW,所以gcc和g ++是我用来编译的.)
我有一个程序来查找数字的倒数,但主程序是用C语言编写的,reciprocal函数是用c ++编写的.接下来我有一个头文件reciprocal.hpp,它有一些条件编译代码,使reciprocal函数成为一个extern函数.Can有人请解释一下reciprocal.hpp程序中有什么.
main.c中
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char **argv)
{
int i;
i = atoi(argv[1]);
printf("\nThe reciprocal of %d is %f\n",i,reciprocal(i));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
reciprocal.cpp
#include<cassert>
#include "reciprocal.hpp"
double reciprocal(int i)
{
assert( i != 0);
return 1.0/i;
}
Run Code Online (Sandbox Code Playgroud)
reciprocal.hpp
#ifdef __cplusplus
extern "C"
{
#endif
extern double reciprocal(int i);
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)
我不明白发生了什么reciprocal.hpp.请帮助!!
我读过了
但是,我还没有找到答案的一个问题:使用extern "C"(例如,尽可能多的函数)是否存在(可能,未来)缺点?
更具体一点:添加extern "C"接口仅使用C功能的函数是否有任何缺点; 换句话说,那些不使用@ k-five答案中列出的功能的人?