I'm trying to create a struct that holds parsing information and i want to create a method that returns the stuct with the data filled in. This is what I have so far but I am getting an error saying Parser.c:3: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘attribute’ before ‘parseString’
Parser.h
#include <stdio.h>
#include <string.h>
typedef struct
{
char* myArguments;
char* myProgramName;
int myNumArguments;
}ParserData;
ParserData parseString(int argc, char** argv);
Parser.c
#include "Parser.h"
ParserData parseString(int argc, char **argv)
{
ParserData tempData;
tempData.myNumArguments = argc;
return tempData;
}
Mish.h
#include "Parser.h"
ParserData myParserData;
Mish.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include "Mish.h"
#define MAXLINE 1024
int main(int argc, char *argv[], char **environ)
{
char buf[MAXLINE];
pid_t pid;
int status;
printf("mish>"); //Print shell
myParserData = parseString(argc, argv);
while (fgets(buf, MAXLINE, stdin) != NULL)
{
buf[strlen(buf) - 1] = 0; /* replace newline with null */
if ( (pid = fork()) < 0)
{
printf("fork error");
}
else if (pid == 0) /* child */
{
execlp(buf, argv[1], (char *) 0);
printf("couldn't execute: %s", buf);
return(127);
}
/* parent */
if ( (pid = waitpid(pid, &status, 0)) < 0)
{
printf("waitpid error");
printf("%% ");
}
}
return(0);
}
2 Answers
Here is one approach (main.c):
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
char* myArguments;
char* myProgramName;
int myNumArguments;
} ParserData;
ParserData * parseString(int argc, char** argv);
int
main(int argc, char const *argv[])
{
ParserData *foo = NULL;
foo = parseString(argc, (char **)argv);
if (foo) {
fprintf(stderr, "myNumArguments: %d\n", foo->myNumArguments);
free(foo);
}
return EXIT_SUCCESS;
}
ParserData *
parseString(int argc, char **argv)
{
ParserData *tempData;
tempData = malloc(sizeof(ParserData));
tempData->myNumArguments = argc;
return tempData;
}
To compile:
$ gcc -Wall main.c -o foo
To run:
$ ./foo
myNumArguments: 1
$ ./foo bar
myNumArguments: 2
This leaves out a lot of error checking code and memory management for the two char * in the structure. Hopefully it will help you figure out what to split into header and implementation files.
Ok so this was not a problem with code but a problem with the files. I noticed the .h files had Mish.h.gch and Parser.h.gch. I deleted the .h's and the .h.gch and recreated the .h files and then compiled with "gcc -o mish Parser.c Mish.c" and it compiled successfully. My guess is that it was a problem with the new code not being updated properly...