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

Is it possible to implement our own function in c language library?

Discussion in 'C' started by johnBMitchell, Apr 9, 2012.

  1. johnBMitchell

    johnBMitchell New Member

    Joined:
    Feb 17, 2011
    Messages:
    38
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    CA, USA
    Home Page:
    When we make program with lots of function then it look complicated because of so much lines. Is it possible to make this function in library? So when I want those function I can called it from library.
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    The basics for a static library would be to compile (no link) the source file containing your functions and then use the compiler's librarian to create the actual library.

    For example, using gcc on the command line, you might try

    Code:
    /* functions.c */
    
    int square(int a) { return a * a; }
    build the library
    Code:
    gcc -c functions.c -o objfile.o
    ar rs libtest.a objfile.o
    program to test the library
    Code:
    /* program.c */
    
    #include <stdio.h>
    
    extern int square(int a); /* prototype */
    
    int main(void) {
    
       printf("square(2) = %d", square(2));
       getchar();
    
       return 0;
    }
    compile the acutal program and link the library
    Code:
    gcc --static -L. -o program program.c -ltest
    Not tested, but I *think* it's along those lines. The command line can be a pain because the paths have to be set in the operating system environment or you'll probably run into "file cannot be found" jibberish.

    CodeBlocks, I think, has a template for both static and dynamic libraries if you'd rather use an IDE... it's free. Other programs will likely have their own syntax and whatnot, so you'd need to mill over the documentation.

    HTH
     

Share This Page