我正在做一项任务,在C++中创建一个MIPS模拟器。我得到了
错误:“临时人员”没有命名类型
错误:“保存”未命名类型
我只是在实现算术部分,并使用三个文件,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 main.cpp
#include "al.h"
#include<fstream>
std::vector<label> labels;
temporaries=malloc(10*sizeof(int));
saved=malloc(10*sizeof(int));
//main()al.cpp
#include "al.h"
using namespace std;
//function definitions我正在使用g++
g++ al.cpp main.cpp al.h 我只是个程序初学者。如果有人能帮我,那就太好了。
编辑
在头文件中使用extern,并声明源文件中的变量,就像稻谷显示的那样,并且它是固定的。谢谢你的帮助!
发布于 2016-10-04 00:28:57
您不能在全局范围级别执行赋值,除非它正在初始化类型。这就是错误信息想要告诉你的。
快速修复方法是将其放在您的主要功能中:
int main()
{
temporaries=malloc(10*sizeof(int));
saved=malloc(10*sizeof(int));
// Other program logic here...
return 0;
}但是请注意,头文件中的声明有问题。temporaries和saved在al.cpp中可见的版本与main.cpp中的不同。为了达到这个目的,你需要这样的东西:
al.h
extern int *temporaries;
extern int *saved;
void al_init();al.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));
}main.cpp
int main()
{
al_init();
return 0;
}当然,现在我们得到了一个奇怪的混合C和C++风格,我将停止进入这个兔子洞。希望这能让你开始工作。
发布于 2016-10-04 00:22:23
要回答这个问题:您的代码需要在一个函数(即main() )中(如果您还没有定义它,那么您无论如何都需要它在你的程序中)。
int main()
{
std::vector<label> labels;
temporaries = static_cast<int*>(malloc(10*sizeof *temporaries));
saved = static_cast<int*>(malloc(10*sizeof *saved));
}一些代码可以在全局范围内执行,但这超出了这个问题的范围。
无独立环境
https://stackoverflow.com/questions/39842391
复制相似问题