1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Help: Call a function

Discussion in 'C' started by maabm78, Mar 5, 2010.

  1. maabm78

    maabm78 New Member

    Joined:
    Mar 5, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Dear All;

    Please could anyone help me. How can I call a function in C file from C++ file?
    Please it is urgent.

    Best regards
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,285
    Likes Received:
    364
    Trophy Points:
    83
    Include the header file and call as a normal function.
     
  3. maabm78

    maabm78 New Member

    Joined:
    Mar 5, 2010
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I did that, but I got "[Linker error] undefined reference to `function_name'".
    I used Dev-C++ compiler.

    I did a simple code.
    Code:
    /*
    * add.h
    */
    #ifndef ADD1_H
    #define ADD1_H
    
    int addnum(int a, int b);
    
    
    #endif
    Code:
    /*
    * add.c
    */
    #include "add.h"
    
    int addnum(int a, int b)
    {
    return a+b;
    }
    
    Code:
    /*
    * main.cpp
    */
    #include <stdio.h>
    #include "add.h"
    
    int main (void) {
    int i,j,z;
    i=4;
    j=5;
    z = addnum(i,j);
    printf("%d\n", z);
    return 0;
    }
     
  4. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    17
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
  5. Abinila

    Abinila New Member

    Joined:
    Feb 20, 2010
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Try this,

    Add the following line in your add.h file. Like,

    Code:
    
    #ifndef ADD1_H
    #define ADD1_H
    #include "add.c"
    
    int addnum(int a, int b);
    #endif
    


    Other wise,



    If you have an individual C function that you want to call, and for some reason you don't have or don't want to #include a C header file in which that function is declared, you can declare the individual C function in your C++ code using the extern "C" syntax. You need to use the full function prototype:

    Code:
    
       extern "C" void f(int i, char c, );
     extern "C" {
       void   f(int i, char c);
       int    g(char* s, char* s2);
    }
    
    Call the function like,

    Code:
    int main()
     {
       f(10, 'x');    
     }
    
     

Share This Page