Thread: Function in other file

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    28

    Function in other file

    I have written a code in a file 4.c

    Code:
    #incldue<stdio.h>
    
    int main() {
         printf("%d",fun(22));
         return 0;
    }
    and one more code in 5.c

    Code:
    int fun(double k) {
         return k;
    }
    And when I compile and run these programs together then it is giving 0 as output , while I was expecting 22.

    Now my question is that if arguments of function in other function in other file are different from that of calling place than what would be the behavior of program.

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You need to write a header file (.h) with the function prototype for your second function in it, and include the header in your main code, just like you did the stdio.h header...
    Code:
    // functions.c
    
    int fun(double k) {
         return k;
    }
    Code:
    // functions.h
    
    #ifndef FUNCTIONS_H
    #define FUNCTIONS_H
    
    int fun(double k); 
    
    
    #endif // functions_h
    Code:
    // main.c
    
    #incldue <stdio.h>
    #include "functions.h"
    
    int main() {
         printf("%d",fun(22));
         return 0;
    }
    Then you need to compile both .c files as part of the same project, and link them together into your executable ... The exact mechanism for that is IDE/Compiler specific so you may want to cruise your help files for answers...

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    > Now my question is that if arguments of function in other function in other file are different from that of calling place than what would be the behavior of program.
    Exactly what you observed.

    In the absense of a prototype, the compiler guessed that fun(22) was passing an integer.
    But in reality, something else was required, so all you got was a junk answer.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fwrite function to write png file stream into a file
    By mdivya in forum C Programming
    Replies: 2
    Last Post: 08-26-2011, 12:10 AM
  2. function in other file
    By nime in forum C++ Programming
    Replies: 11
    Last Post: 10-12-2010, 11:56 PM
  3. Replies: 3
    Last Post: 11-21-2006, 07:26 PM
  4. Replies: 30
    Last Post: 06-19-2006, 12:35 AM
  5. *.h file, function definitions.. help
    By jstevanus in forum C++ Programming
    Replies: 2
    Last Post: 12-08-2004, 03:15 PM