LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Linux Answers > Programming
User Name
Password

Notices


By crabboy at 2003-08-12 14:26
HowTo build simple C programs on Linux

1. Introduction

This document will step you though compiling and running simple C programs under the Linux operating system. It is meant as a guide for beginners who may know how to program in C but don't know how to build a C program on Linux. This document uses simple C programs to illustrate how to build the programs under Linux. It covers writing a basic C program but it is not meant as a guide to teach the language. We will also step through the basics of writing a Makefile for your project.

This document also assumes that you know how to create/edit files on Linux and that you have the GNU C compiler installed. An easy way to tell if you have a C compiler installed is by issuing the command 'which gcc'. We are also assuming that the compile is executed from the command line. There are far too many GUI/IDE type environments to cover otherwise.

2. A Simple program

2.1 Writing the source

The source of our first program is below:
Code:
#include <stdio.h>

main()
{
  printf("Linuxquestions.org\n");
}
Save the program above and call it simplelq.c

Here is the breakdown of the program above.
The first line #include <stdio.h> is a preprocessor directive. This basically tells the compiler that we are using the functions that are in the stdio library. The stdio library contains all the basic functions needed for basic input and output for our program.

The second line main() is a required function for every C program. main() is the starting point for the program. Like all functions the body begins with a { (open curly brace) and ends with a } (close curly brace).

The body of our main function printf ("Linuxquestions.org\n"); is a function call to the printf function. printf stands for print formatted and has complex rules for printing text, numbers to specific formats. Here we are just displaying the test "Linuxquestions.org" to the screen. The \n at the end of string is a newline. It tells printf to end the line and start any additional text on the next line. All function calls in C must end in a ;

2.2 Compiling the Source

The compile is done from the command line.

Code:
$  gcc -o simplelq simplelq.c
$
gcc is the GNU C compiler. The -o option tells it what to name the output file and the simplelq.c is the source file.

The output from the compiler will be a binary file called simplelq

2.3 Running the executable

In order to run our sample executable we will need to apply the execute permission to the file. The we will execute it after.
Code:
$  chmod 744 simplelq
$  ./simplelq 
Linuxquestions.org
The output of our sample program produced the text "Linuxquestions.org" to the console (or screen). Try to add some more text to the sample program, recompile and watch the output.

3. Dealing with multiple sources

In most projects that are more that a couple functions you will most likely want to split out the source into multiple files. Splitting the code allows the source to be more manageable by avoiding huge source files and to group like functions together.
Here is an example that has multiple sources:

3.1 The source files
Code:
 
/* File: appendall.h */

/* below is a forward deceleration of a function.  It differs from a 
function header by the semicolon at the end.  Any source that wants to 
use the appendall function needs to include this header file. */

void appendall( int iArgCount,
                char * iArgs[],
                char * szReturnBuffer,
                int iSize );
Code:
/* File: appendall.c */

#include <stdio.h>


void appendall( int iArgCount,
               char * iArgs[],
               char * szReturnBuffer,
               int iSize )
{
  int i = 0;
  
  for ( i = 0; i < iArgCount; i++ ) /* Loop through all the arguments */
  {
      /* Test to see if the added length of the new arg will exceed */
      /* the length of our buffer */

     if (( strlen( szReturnBuffer ) + strlen( iArgs[i] )) < iSize )
     {
        strcat( szReturnBuffer, iArgs[i] ); /* concatenate */
        strcat( szReturnBuffer, " " );      /* add a string */
     }
     else
     {
        printf( "Error:  exceeded buffer size\n");
        break;
     }
  }
}
Code:
/* File appendallmain.cpp */

*/ This include will pull in the function declaration for appendall.h 
*/
#include "appendall.h"

#define SIZE 500

main( int argc, char * argv[])
{
  char szNewString[SIZE]; /* declare a character array of size 500 */

  appendall( argc, argv, szNewString, SIZE );  /* Call the function */
  printf("%s", szNewString );
}
3.2 Compiling the Source

The compile is done from the command line.

There are a couple ways to do this. One is to compile and link in one step and the other is to build the objects separately and then link.

Compile and link multiple sources in one step.
Code:
$  gcc -o appendall appendall.c appendallmain.c
$
Compile and link in multiple steps:
Code:
$ gcc -c appendall.c 
$ gcc -c appendallmain.c
$ gcc -o appendall appendall.o appendallmain.o
$
The -c flag tells the compiler to compiler only and not call the linker.

It is easier to build and link in one step, but if you are using Makefiles to manage your project the separate compile and link makes building much quicker.

Here is a simple Makefile for building the above sources:
Code:
all:     appendall

appendall.o:     appendall.c appendall.h
    gcc -c appendall.c

appendallmain.o:     appendallmain.c appendall.h
    gcc -c appendallmain.c

appendall:     appendall.o appendallmain.o
    gcc -o appendall appendall.o appendallmain.o

clean: 
    rm *.o appendall
Run make to build the sources:
Code:
$ make
gcc -c appendall.c
gcc -c appendallmain.c
gcc -o appendall appendall.o appendallmain.o
$
Here is the basic breakup of a Makefile rule:

target ... : prerequisites ...
command
...
...


There must be a <tab> character before all the commands after a rule. Spaces instead of tabs will result in errors.

4. Suggest Links

http://www.gnu.org/software/gcc/gcc.html
http://www.gnu.org/software/make/manual/make.html
http://www.linuxquestions.org/questions/search.php

by darin3200 on Wed, 2003-08-13 20:11
Looks nice. Hopefully java expierence will be helpful, I want to learn C and my school never has enough people sign up for the class to have it. Thanks

by genesis1923 on Thu, 2003-08-14 04:22
Looks good but my problem is that SuSE Office desktop does not come with a C compiler. What would be really useful for me is a section on how to get started if you don't have a C compiler.

by svar on Thu, 2003-08-21 09:42
??? what do you mean Suse does not come with a C compiler?
gcc is the GNU C compiler
and it is packaged with Suse, last time I checked(up to SuSe 8)

svar

by jim mcnamara on Fri, 2003-10-31 17:32
make comment:

under several flavors of unix make does not require tab characters in rules. They don't break anything if they are there.

The other thing which confuses new folks : K&R, ANSI "styles"
Code:
/* ----- version 1 */
int main(argc, argv)
int argc;
char **argv;
{
       return 0;
}

/* ---- version 2 */
int main(int argc, char *argv[])
{
       return 0;
}

/* --------- version 3 */
int main(int argc, char *argv[]){
        return 0;
}
Believe it or not, C shops usually prefer style #3 - very 'ANSI'
Style 2 is "okay", style 1 is a no-no.

A lot of examples I've seen that come with downloads were written in 1985 and look like version 1.

While it doesn't REALLY matter, this is confusing as hell to newbies.

You might want to consider adding a section talking about style.
Plus, version 1 won't compile under cc -Aa on HPUX v11.0 for example. So, it can cause some issues down the road.

by wilson-china on Tue, 2004-03-02 22:49
a good subject

by Dazed_75 on Fri, 2006-01-20 00:57
Although you begin the article saying it is inended for folks who know C but do not know how to build a program under Linux, you spend much of the article expplaining the simple C program. You spend very little of the article saying how building it is different in Linux. I have some 15= year old experience In C under DOS, Windows and Unix (a little). I was hoping to see this article show how to set up my environment under Linux and how some of the tools differ or have improved.

When I saw the first line in the 1st program as "#include" with no argument as to WHAT to include and your statement that it meant you were using the stdio library, I thought I was on the right track. However, gcc gives the expected errors on that line (yes, I named the file differently):

inctest.c:1:9: error: #include expects "FILENAME" or <FILENAME>
inctest.c: In function ‘main’:
inctest.c:5: warning: incompatible implicit declaration of built-in function ‘printf’

I infer not that your article is wrong, but that your environment is set up differently. Specifically, I found some other articles referring to default includes but they did not help either. Now I don't mind; in fact, I like being explicit about my includes so this is not a big deal detail. What I would like to find though is some information that really IS about how building C programs in Linux is different from other environments. Any suggestions?

by robin2190 on Sat, 2006-01-21 10:35
how do i install simply mepis 2004 2.6.7.? HELPPPPPPPPP

by Darkhack on Mon, 2006-03-20 14:45
Quote:
Originally Posted by Dazed_75
When I saw the first line in the 1st program as "#include" with no argument as to WHAT to include and your statement that it meant you were using the stdio library, I thought I was on the right track. However, gcc gives the expected errors on that line (yes, I named the file differently):

inctest.c:1:9: error: #include expects "FILENAME" or <FILENAME>
inctest.c: In function ‘main’:
inctest.c:5: warning: incompatible implicit declaration of built-in function ‘printf’
Sadly, the author must have forgotten that his text would be displayed "as-is" in a browser and that they don't render < or > very well. In order to display the greater-than or less-than signs, you must use the following... (hopefully the author will fix it)

> = &gt;
< = &lt;

by xushi on Sat, 2006-03-25 13:07
I understand the author's kind intentions, but this is a very poor article. I'm not sure how the LQ mods allowed it to be posted, and furthermore, i'm not sure why or how the author didn't preview his work, or check/fix any mistakes afterwards. I'm not referring to tricky or blind-eye mistakes, but big ones such as the #include bit on the top.

Furthermore, adding to the comments said above, this hasn't really shown us any differences between building a typical C program, and building a C program for Linux.

And as an added suggestion, some outside links to more indepth tutorials for certain sections would do good.

I hope this article gets fixed. It is valuable and it's needed in LQ.

by kumar.anupam on Tue, 2008-02-19 02:29
where does the temporary variables gets stored while executing C program.


  



All times are GMT -5. The time now is 04:46 AM.

Main Menu
Advertisement
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration