Reputation:
I know that in programming it is important to keep things simple and be able to be changed. So to me that means it is important to use different files and functions and to keep them separate to easier isolate faults and improve readability.
I am new to C and I don't understand how to do this. I have my nodeTest.h
#include <stdio.h>
#include <stdlib.h>
struct nodeTest
{
int data;
struct nodeTest* next;
};
Then I have another file trying to call that struct
#include <stdio.h>
#include <stdlib.h>
#include "nodeTest.h"
nodeTest* first = (nodeTest*)malloc(sizeof(nodeTest));
I am getting an error saying that nodeTest is undeclared(not in function). What does that mean and why can I not use include to include a struct or typedef?
Upvotes: 0
Views: 81
Reputation: 42083
Within global scope, you can just declare / define functions, structures or global variables. You can not call a function just like that (literally "out of nowhere"). Create a main
and call malloc
from within:
int main(void) {
nodeTest* first = (nodeTest*) malloc(sizeof(nodeTest));
free(first);
return 0;
}
struct nodeTest {
int data;
struct nodeTest* next;
};
defines struct nodeTest
so
nodeTest* first;
is unknown to compiler. To solve this you could either use:
struct nodeTest* first;
or even better: use typedef
while defining your struct
and everything will be fine:
typedef struct nodeTest {
int data;
struct nodeTest* next;
} nodeTest ;
Upvotes: 1
Reputation: 14174
You have to use struct NodeTest
instead of NodeTest
.
Thats because C differentiates three namespaces:
So everywhere you want to use an struct, you have to specify the compiler that name refers to an struct. For example:
int main()
{
struct NodeTest node;
}
One workaround to that problem is to specify an alias to that struct, to "add" the struct to the types namespace:
typedef NodeTest NodeTestType;
int main()
{
NodeTestType node; //OK
}
Or using the common idiom, declare directly the struct as an alias:
typedef struct { ... } NodeTest;
Note that what this sentence does is to make an alias named NodeTest
to an unnamed struct
you have declared in the same instruction.
One problem of this approach is that you cannot use the type inside the struct, because its not declared yet. You could workaround it naming the struct:
typedef struct nodeTest //<-- Note that the struct is not anonimous
{
int data;
struct nodeTest* next;
} nodeTest;
Upvotes: 2
Reputation: 7044
Just put your code inside a function like this:
#include <stdio.h>
#include <stdlib.h>
#include "nodeTest.h"
int main(void) {
struct nodeTest* first = malloc(sizeof(struct nodeTest));
return 0;
}
Upvotes: 0
Reputation: 10516
you need to define nodetest type
typedef struct nodeTest_t
{
int data;
struct nodeTest_t* next;
}nodeTest;
or else
in main(), use struct
keyword before nodeTest.
Upvotes: 0