Thread: implicit declaration of function ‘close’

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    45

    implicit declaration of function ‘close’

    Hi,
    I wrote a simple piece of code as an exercise in file_descriptors which opens a file and then closes it using open and close. When I try to compile it using the flags -Wall -ansi -Werror with gcc, the get this error.

    implicit declaration of function ‘close’

    heres the code.
    Code:
    /* sample code to open and close a file using file descriptors */
    
    #include <stdio.h>
    #include <fcntl.h>
    #include <stdlib.h>
    
    int main(){
    
            int file_descriptor,error_code;
            char filename[] = "sample_text.txt";
    
            file_descriptor = open(filename, O_WRONLY | O_CREAT | O_EXCL);
    
            if(file_descriptor == -1) {
                    perror("cannot open file\n");
                    exit(1);
                    }
    
            /* close the opened file */
            error_code = close(file_descriptor);
    
            if(error_code == -1){
                    perror("cannot close file\n");
                    exit(1);
                    }
    
            return 0;
    }
    Can anyone throw some hint?

    -Livin

  2. #2
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    The close() system call is declared in unistd.h, which you have not included. That's why you get a warning about implicit declaration.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Oddly, close is in another header file to open
    NAME
    close - close a file descriptor

    SYNOPSIS
    #include <unistd.h>

    int close(int fd);
    But unistd does have read/write/seek as well, so that's the end of the weirdness.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Mar 2011
    Posts
    45
    oh ok. I included the unistd.h and it worked. thanks you two!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Implicit Declaration Of Function
    By nathanpc in forum C Programming
    Replies: 1
    Last Post: 01-26-2010, 08:46 PM
  2. implicit declaration of function?
    By BoneXXX in forum C Programming
    Replies: 2
    Last Post: 04-27-2007, 11:04 PM
  3. Implicit declaration of function ...???
    By soothsayer in forum C Programming
    Replies: 8
    Last Post: 08-07-2006, 06:49 AM
  4. Implicit declaration of function
    By soothsayer in forum C Programming
    Replies: 5
    Last Post: 02-28-2006, 02:56 PM
  5. Implicit declaration of function : wait()
    By husust in forum C Programming
    Replies: 2
    Last Post: 02-06-2006, 09:35 AM