所以我用它创建目标文件
cc -c MAIN.C
cc -c tablero.c
Run Code Online (Sandbox Code Playgroud)
但是当我尝试将它们链接到可执行文件时
cc MAIN.o tablero.o
Run Code Online (Sandbox Code Playgroud)
我明白了
undefined reference to `asdf()'
Run Code Online (Sandbox Code Playgroud)
(在tablero.c中定义并在MAIN.C中调用的函数)
这是我的文件:
我有MAIN.C
#include <stdio.h>
#include <cstring>
#include "tablero.h"
int main()
{
int c;
printf( "Enter a value :");
c = getchar( );
putchar(c);
printf( "\nYou entered: ");
c = asdf ();
putchar(c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我有tablero.h
#ifndef TABLERO_H_
#define TABLERO_H_
int asdf();
#endif // TABLERO_H_
Run Code Online (Sandbox Code Playgroud)
我有tablero.c
#include "tablero.h"
int asdf() {return 48;}; //48 is 0 in ascii
Run Code Online (Sandbox Code Playgroud)
zwo*_*wol 20
cc在许多Unix系统上,你被这个工具的一个模糊特征所困扰:后缀为小写的文件.c被编译为C,但后缀为大写的 文件.C被编译为C++!因此,您的main(编译为C++)包含对受损函数名称的外部引用asdf()(又名_Z4asdfv),但tablero.o(编译为C)仅定义一个未编码的名称asdf.
这也是您能够将C++头文件包含<cstring>在C程序中的原因.
重命名MAIN.C为main.c(并更改<cstring>为<string.h>),重新编译main.o,您的程序应该链接.
如果您确实想要将程序的一部分编译为C而将部分编译为C++,那么您可以使用extern "C"以使符号匹配来标注头文件:
#ifndef TABLERO_H_
#define TABLERO_H_
#ifdef __cplusplus
extern "C" {
#endif
int asdf(void);
#ifdef __cplusplus
}
#endif
#endif // TABLERO_H_
Run Code Online (Sandbox Code Playgroud)
像这样的头文件必须格外小心,只包含在C和C++中具有相同含义的代码.只有POD类型,没有C++关键字,没有C99但不是C++关键字,没有重载,等等.
| 归档时间: |
|
| 查看次数: |
3272 次 |
| 最近记录: |