简体   繁体   English

C / C ++:在我的库中使用extern的正确位置吗?

[英]C/C++: Proper places to use extern for my library?

I am making a shared library and its functions remained undefined during linking when built (and linking with a test program), and now I have learned name mangling and why it would cause something like this. 我正在创建一个共享库,并且在构建时(以及与测试程序的链接)链接期间,其功能仍未定义,现在我了解了名称修饰以及为什么会引起这种情况。

I assume in the libfoo.h header I would put: 我假设在libfoo.h标头中输入:

#ifdef __cplusplus
  extern "C" {
#endif
int foobar();
#ifdef __cplusplus
  }
#endif

And would the externs for the prototypes be all I need to apply them to, or would I need to wrap them around the function declarations in libfoo.c as well so my C++ program can read them? 原型的外部要素是我需要应用于它们的全部,还是我也需要将它们包装在libfoo.c中的函数声明周围,以便我的C ++程序可以读取它们?

Update for comment below: 更新以下评论:

The linking error is this: 链接错误是这样的:

g++ prototypes.cxx -L/usr/lib/  -lfoo
/tmp/ccKQmen4.o: In function `main':
prototypes.cxx:(.text+0x19): undefined reference to `foobar()'
collect2: ld returned 1 exit status

You don't have to do anything with the source, as long as you compile it with a C compiler. 只要使用C编译器对其进行编译,您就不必对源代码执行任何操作。

That's what you tell the C++ compiler in the header - use C calling and nameing conventions. 这就是您在标头中告诉C ++编译器的内容-使用C调用和命名约定。

The C++ FAQ has a whole section devoted to mixing C and C++ http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.4 C ++常见问题解答有一整节专门介绍C和C ++的混合使用http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html#faq-32.4

Basically the only place to put extern "C" is in those header files included from C and C++. 基本上,唯一的放置extern "C"是C和C ++包含的那些头文件中。 If you don't have control over those, follow the previous answer (32.3). 如果您无法控制这些,请遵循前面的答案(32.3)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM