Thread: "Including" other programs

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    98

    "Including" other programs

    If I have written some functions ina program p1.c, and would like to call those functions from another program, p2.c, what do I need to do to #include the p1.c program in the p2.c program?

    Thanks.

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Declare the funcs in p1.c in a header file and #include that in p2.c...then call the funcs you need

  3. #3
    Registered User
    Join Date
    Oct 2002
    Posts
    98
    Sorry to labour the point, but how do I declare the functions in p1.h, and how do I indicate that the functions I have declared can be found in p1.c?

    Thanks again!!

  4. #4
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    When you run the compiler/linker, you need to specify both source files. The linker will take care of making the functions in P1.C available to P2.C

    But for the compiler to work properly, the routines defined in P1 must be 'prototyped' in P2 (look it up, you'll find information lots of places) and that's where Fordy's message becomes very useful. Add the prototypes to P1.H and #include this file in P2.C

    Walt

  5. #5
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,793
    Here's an example

    Test1.cpp
    Code:
    #include "Test2.h"
    
    int main()
    {
    	foobar();
    }
    Test2.cpp
    Code:
    #include <iostream>
    
    void foobar()
    {
    	std::cout << "Hello World";
    }
    Test2.h
    Code:
    void foobar();

  6. #6
    Registered User
    Join Date
    Feb 2003
    Posts
    76
    It is not usually advisable to include an entire C file in another header file, because any changes in the included file will cause all files that include the file to be recompiled. This approach will also cause unnecessary copies of function definitions to appear in the resulting program.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Starting programs
    By Molokai in forum C Programming
    Replies: 1
    Last Post: 04-16-2009, 10:10 AM
  2. Recommend upgrade path for C programs
    By emanresu in forum C Programming
    Replies: 3
    Last Post: 11-22-2007, 07:32 AM
  3. Newbie question: pointers, other program's memory
    By xxxxme in forum C++ Programming
    Replies: 23
    Last Post: 11-25-2006, 01:00 PM
  4. POSIX/DOS programs?
    By nickname_changed in forum C++ Programming
    Replies: 1
    Last Post: 02-28-2003, 05:42 AM
  5. executing c++ programs on the web
    By gulti01 in forum C++ Programming
    Replies: 4
    Last Post: 08-12-2002, 03:12 AM