Ayush Prakash
Ayush Prakash

Reputation: 13

C++ : Error does not name a type

I am working on an assignment to create a MIPS Simulator in C++. I got
error: 'temporaries' does not name a type
error: 'saved' does not name a type
I am just implementing the arithmetic part and am using three files, 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

I am using g++

g++ al.cpp main.cpp al.h 

I am just a beginner in progamming. It will be great if anyone can help me out.

Edit

Used extern in the header files and declared the variables in the source files just like paddy showed and it was fixed. Thanks for all the help!

Upvotes: 1

Views: 4956

Answers (2)

krzaq
krzaq

Reputation: 16431

To answer the question: your code needs to be inside a function¹, i.e. main() (you need it in your program² anyway, if you haven't defined it already).

int main()
{
    std::vector<label> labels;
    temporaries = static_cast<int*>(malloc(10*sizeof *temporaries));
    saved = static_cast<int*>(malloc(10*sizeof *saved));
}

¹ some code can be executed at global scope, but that's beyond purview of this question

² sans freestanding environment

Upvotes: 1

paddy
paddy

Reputation: 63481

You can't do the assignment at the global scope level, unless it is initialising a type. That's what the error messages are trying to tell you.

The quick fix is to put it in your main function:

int main()
{
    temporaries=malloc(10*sizeof(int));
    saved=malloc(10*sizeof(int));

    // Other program logic here...

    return 0;
}

But note that you have a problem with the declaration in the header file. The version of temporaries and saved visible within al.cpp is not the same as in main.cpp. In order to achieve that, you need something like this:

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;
}

Of course, now we're getting a strange blend of C and C++ style, and I'm going to stop going down this rabbit hole. Hope this helps to get you started.

Upvotes: 6

Related Questions