LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   I need help using multiple source files (https://www.linuxquestions.org/questions/programming-9/i-need-help-using-multiple-source-files-128950/)

CodeWarrior 12-25-2003 10:45 PM

I need help using multiple source files
 
Most of the C/C++ programs I have written contain all my variables and functions in one file with a main(). I want to learn how to split my code between multiple files, but it seems that I have never been showed how to do this. The main reason I want to do this is because I want to be able to put functions that I commonly use into a file and compile it with the file that contains main(). Does anyone have a tutorial that shows how to do this? Only one fiel can contain the function main(), correct? If this is so how do these other source files look?

stuNNed 12-26-2003 12:44 AM

newbie response:: you can create other functions as files and even functions within functions you just need to call them after they are defined or something. bash handles this quite well.

jeempc 12-26-2003 11:21 AM

Here is one way.
Put your function definations in a file called myfunctions.c . Or whatever name you want. Put the function declarations in a file called myfunctions.h
In main do this.

# myprogram.c
#include <stdio.h> // or whatever you use
#include "myfunctions.h" // put this file in the same directory as main

main()
{
...
}

Now to complile

gcc myprogram.c myfunctions.c

That should work.
Jeem

vasudevadas 12-29-2003 10:27 AM

The long-winded way to do it, as per jeempc's example, is to first do:

gcc -c myfunctions.c
gcc -c myprogram.c

That should create myfunctions.o and myprogram.o. Then do:

gcc -o myprogram myfunctions.o myprogram.o

which will create myprogram, an executable file. If you're entering the gcc command by hand then you'll want to do what jeempc told you. If you were to write a makefile to automate your compilation (you'll want to do this if your project included many files) then you'd want to do it my way.

UltimaGuy 12-30-2003 04:18 AM

I think the solution is makefiles. It will help you automate your compilation from among multiple source file.

Go here --> http://www.linuxselfhelp.com/gnu/mak.../make_toc.html for learning about makefiles.


All times are GMT -5. The time now is 01:54 PM.