c++ - extern "C"按着别人博客写的测试程序总是报错?
大家讲道理
大家讲道理 2017-04-17 15:03:40
0
2
632

三个文件:

/* c语言头文件:cExample.h */
#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
extern int add(int x,int y);     //注:写成extern "C" int add(int , int ); 也可以
#endif
/* c语言实现文件:cExample.c */
#include "cExample.h"
int add( int x, int y )
{
 return x + y;
}
// c++实现文件cppFile.cpp,调用add
extern "C"
{
#include "cExample.h"
}
//注:此处不妥,如果这样编译通不过,换成 extern "C" int add(int , int ); 可以通过
extern "C" int add(int, int);
int main(int argc, char* argv[])
{
    add(2, 3);
    return 0;
}

这都是别人博客的代码,他说不会错,然后我在VS2015运行了,报错,错误 LNK2019 无法解析的外部符号 _add,该符号在函数 _main 中被引用。我换了好几个人博客把代码复制进去都是报同样的错误,我不知道是什么问题,上面注释里的我也试了还是报错。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
Peter_Zhu

The error was found,

I didn’t drag .c and .h into the project, I just placed them in this directory. Resolved.

Ty80

I just saw that the original poster has solved the problem himself. However, this example is still wrong here in gcc:

$ g++ -std=c++11 -pedantic -Werror cExample.c cppFile.cpp -o demo
/tmp/cceHYgc4.o: In function `main':
cppFile.cpp:(.text+0xf): undefined reference to `add'
collect2: error: ld returned 1 exit status

This is because when the c++ compiler compiles cExample.c, although your intention is to call the C compiler to compile the code of the add function, the c++ compiler does not know this. It thinks that the add function It is a c++ function, so after compilation, the name of the add function will be changed to _Z3addii. In this way, even if you specify to use the C version of the add function in the cppFile.cpp file, this function does not actually exist, so an unresolved external symbol appears.

To solve this problem, just write this in the cExample.h file:

#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
extern "C" {
        int add(int x, int y);
}
#endif

If the function declared in cExample.h is to be called by other C modules, the strict writing method is:

#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
#ifdef __cplusplus
extern "C" {
#endif

int add(int x, int y);

#ifdef __cplusplus
}
#endif
#endif

As for why dragging cExample.{h,c} into the project in VS can solve the problem, it is unknown. My guess is that when VS encounters a file with the file extension .c, it automatically uses the C compiler to compile it.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!