我有一个C程序,需要与C++库(ROS)进行接口(interface)。通常,使用extern "C"
并使用C++编译器链接使用包装器将C代码与C++代码进行接口(interface)并不是很困难,但是我不需要在main
位于C部分的情况下这样做。
C++ FAQ表示这是一件坏事:
但是这些天我看到another source saying it should be okay:
main
是在C部分还是C++部分中为什么会很重要?如果我现在尝试使用常见的链接器(主要是GCC和Clang的)链接C部分中的代码,那将会有多少麻烦?
最佳答案
解决此问题的一种简单方法是重命名C main()并从新的C++ main()调用它
如:
// in ypur current C main module
int my_c_main(int argc, char* argv[]) /* renamed, was main() */
{
/* ... */
]
// in a c++ module...
int main(int argc, char* argv[])
{
extern "C" int my_c_main(int argc, char* argv[]);
// if your c main() requires environment variables passed in envp,
// You can allocate space for strings and an array here and pass
// the environment variables you'll need, as the third parameter
// to my_c_main(), or pass environ, if your system has
// it defined in unistd.h
return my_c_main(argc, argv);
}
关于c++ - 在混合C和C++代码时,main()是否需要在C++部分中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/66192195/