Hanna
Hanna

Reputation: 539

GCC errors out on code that used to work fine

I have a program that has successfully compiled in the past, but now I get a bunch of errors.The source code is just:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

int main()
{
    int fd;
    fd = creat("datafile.dat", S_IREAD | S_IWRITE);
    if (fd == -1)
        printf("Error in opening datafile.dat\n");
    else
    {
        printf("datafile.dat opened for read/write access\n");
        printf("datafile.dat is currently empty\n");
    }
    close(fd);
    exit (0);
}

Now I get the errors:

cre.C:8:54: error: ‘creat’ was not declared in this scope
cre.C:16:17: error: ‘close’ was not declared in this scope
cre.C:17:16: error: ‘exit’ was not declared in this scope

Sometimes I get an error about gxx_personality_v0 instead, and sometimes I get no error at all! I've tried updating gcc, but the problem remains. What's going wrong? OS UBUNTU 12.1 on vaio laptop

Upvotes: 0

Views: 287

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263237

Read the man pages for the creat, close, and exit functions.

On my system, creat() requires:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

close() requires:

#include <unistd.h>

and exit() requires:

#include <stdlib.h>

As for why the code was compiling before, it's hard to tell. Perhaps the compiler was being invoked in a more permissive mode that didn't complain about missing function declarations, or perhaps some of the headers you do include have #include directives for the headers you need.

Upvotes: -1

Renan
Renan

Reputation: 462

From your error messages I see that you called your file cre.C. gcc is case-sensitive for file names: try naming it cre.c and compiling it.

$ LANG=C cc -o foo foo.C
foo.C: In function 'int main()':
foo.C:8:54: error: 'creat' was not declared in this scope
foo.C:16:17: error: 'close' was not declared in this scope
foo.C:17:16: error: 'exit' was not declared in this scope

but

$ LANG=C cc -o foo foo.c
foo.c: In function 'main':
foo.c:17:9: warning: incompatible implicit declaration of built-in function 'exit' [enabled by default]

As noted in a comment, a file with .C extension is handled by the C++ compiler, thus you are seeing those errors.

Upvotes: 5

Related Questions