clinuxgccheader-files

C program not compiling when using headers


(C PROGRAM) I'm trying to compile a main.c that uses a header but I'm getting the errors below. When I don't use the header (all methods in the main file) everything works.

In a string S, the program find all words occurrences and returns the word that appears the most.

I'm compiling using: gcc main.c

Thank you.

errors

In file included from main.c:9:0:
frequence.h:4:16: warning: useless storage class specifier in empty declaration [enabled by default]
main.c: In function ‘main’:
main.c:15:10: error: variable ‘word’ has initializer but incomplete type
main.c:15:10: warning: passing argument 1 of ‘show_all_words’ from incompatible pointer type [enabled by default]
frequence.h:6:17: note: expected ‘char *’ but argument is of type ‘char (*)[34]’
main.c:15:10: error: invalid use of undefined type ‘struct stat_mot’
main.c:15:19: error: storage size of ‘word’ isn’t known

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "frequence.h"

#define LONGUEURMAX 4

int main(char *argv[]) {
  char texte[] = ";! one two, tree foor one two !:;";
  struct stat_mot word = show_all_words(&texte);

  printf("%s : %d\n", word.word, word.frequency);

  return (EXIT_SUCCESS);
};

frequence.h

#ifndef DEF_FREQUENCE
#define DEF_FREQUENCE

typedef struct stat_mot;
int count_word(char * , char * );
struct stat_mot show_all_words(char *);

#endif

frequence.c

#include "frequence.h"

typedef struct stat_mot {
    char * word;
    int frequency;
} stat_mot;

int count_word(char * mot, char * text) {
  int n = 0;
  char *p;

  p = strstr(text, mot);  
  while (p != NULL) {
    n++;
    p = strstr(p + 1, mot);
  }  

  return n;
}

stat_mot show_all_words(char * text) {
    char * text_rw = strdup(text);
    char * p = strtok(text_rw, " .,;:-!?");

    char word_to_return[strlen(text)];
    int  word_frequence = 0;

    while (p != NULL) {
      if (strlen(p) >= 0) {
        int offset = p - text;
        int count = count_word(p, text);

        if (word_frequence < count) {
          strcpy(word_to_return, p);          
          word_frequence = count;
        }
      };

      p = strtok(NULL, " .,;:-!?");
    }

    free(text_rw);
    struct stat_mot word = { word_to_return, word_frequence };
    return word;
}

Solution

  • You must put your stat_mot structure in frequence.h.

    Additionally, main() should be declared like

    int main(int argc, char **argv)
    

    and texte should be a char *:

    int main(char *argv[])
    {
        char *texte = ";! one two, tree foor one two !:;";
        struct stat_mot word = show_all_words(texte);
    

    You also ought to include <string.h> and <stdlib.h> in frequence.c since you use strstr, strlen and free.

    In frequence.c, strlen is always greater or equal to zero, so the comparison will always be true.