1 c++
我正在从事一项用 C++ 创建 MIPS 模拟器的任务。我收到
错误:'temporaries' 未命名类型
错误:'saved' 未命名类型
我只是在实现算术部分并且正在使用三个文件,main.cpp、al.cpp、al.h。
al.h
#ifndef AL_H
#define AL_H
#include<vector>
#include<string>
#include<cstdlib>
#include<iostream>
int *temporaries;
int *saved;
typedef struct
{
std::string name;
int value;
}label;
//function declarations
#endif
Run Code Online (Sandbox Code Playgroud)
主程序
#include "al.h"
#include<fstream>
std::vector<label> labels;
temporaries=malloc(10*sizeof(int));
saved=malloc(10*sizeof(int));
//main()
Run Code Online (Sandbox Code Playgroud)
cpp文件
#include "al.h"
using namespace std;
//function definitions
Run Code Online (Sandbox Code Playgroud)
我正在使用 g++
g++ al.cpp main.cpp al.h
Run Code Online (Sandbox Code Playgroud)
我只是编程的初学者。如果有人可以帮助我,那就太好了。
编辑
使用extern的头文件,并宣布在源文件中,就像稻田显示变量,它是固定的。感谢所有的帮助!
您不能在全局范围级别进行分配,除非它正在初始化类型。这就是错误消息试图告诉您的内容。
快速修复是将它放在您的主要功能中:
int main()
{
temporaries=malloc(10*sizeof(int));
saved=malloc(10*sizeof(int));
// Other program logic here...
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但请注意,您在头文件中的声明有问题。中的temporaries和saved可见的版本与al.cpp中的不同main.cpp。为了实现这一点,你需要这样的东西:
al.h
extern int *temporaries;
extern int *saved;
void al_init();
Run Code Online (Sandbox Code Playgroud)
cpp文件
// These are the actual symbols referred to by the extern
int *temporaries = nullptr;
int *saved = nullptr;
// Since these belong to `al`, initialize them in that same source unit.
void al_init()
{
temporaries=malloc(10*sizeof(int));
saved=malloc(10*sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)
主程序
int main()
{
al_init();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当然,现在我们得到了 C 和 C++ 风格的奇怪混合,我将停止进入这个兔子洞。希望这有助于您入门。
| 归档时间: |
|
| 查看次数: |
2989 次 |
| 最近记录: |