C programming language - ch1

Home

Table of Contents

1 Compiling the examples

Compile with the standard ./configure ; make

Additionally add the following make options to turn off optimizations and enable debugging symbols

./configure

make CXXFLAGS='-g3 -Wall -O0 '  CFLAGS='-g3 -Wall -O0 '

when building C samples, you can also create separate build directory

mkdir build
cd build
../configure
make

2 Autotools template example

Please check the Autotools template example

3 examples

3.1 configure.ac

#                                               -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.

AC_PREREQ([2.68])
AC_INIT([tacpl_ch1], [0.1], [snarvaezsoft@gmail.com])
##AM_INIT_AUTOMAKE([-Wall -Werror])
AM_INIT_AUTOMAKE([-Wall -Werror])
AC_CONFIG_SRCDIR([config.h.in])
AC_CONFIG_HEADERS([config.h])

# Checks for programs.
AC_PROG_CC

# Checks for libraries.
# FIXME: Replace `main' with a function in `-lm':
AC_CHECK_LIB([m], [abs])

# Checks for header files.
AC_CHECK_HEADERS([stdlib.h])

# Checks for typedefs, structures, and compiler characteristics.

# Checks for library functions.
AC_CHECK_FUNCS([pow])

AC_CONFIG_FILES([Makefile
                 src/Makefile])
AC_OUTPUT

3.2 Makefile.am

## Makefile.am -- Process this file with automake to produce Makefile.in

SUBDIRS = src

3.3 src/Makefile.am

## Makefile.am -- Process this file with automake to produce Makefile.in

## To enable debug symbols and all warnings, compile with:
## make clean
## make CXXFLAGS='-g -Wall -O0 '  CFLAGS='-g -Wall -O0 '


## Append to CFLAGS.  Used by gcc to compile c programs
AM_CFLAGS =  -std=gnu11

## Append to CXXFLAGS. Used by g++ to complite cpp programs
AM_CXXFLAGS = -std=c++11


bin_PROGRAMS = linecount arrayCount hexa histogram \
        inout longestline testpow wordcount wordsplit    \
        exercise1_7 exercise1_9 exercise1_12 countchars_2nd

# executes when run  "make check"
check_PROGRAMS = celsius

# if a program consist of only a .c file,  no need to add a _SOURCES section
linecount_SOURCES = linecount.c


testpow_SOURCES  = testpow.c
#testpow_LDADD =
testpow_LDFLAGS = -lm



#main_LDADD = @LEXLIB@

3.4 src/celsius.c

download => celsius.c

#include <stdio.h>

/* print Fahrenheit-Celsius table 
 * for fahr = 0, 20, ..., 300 ; floating-point version */

main() {
        float fahr, celsius;
        float lower, upper, step;

        lower = 0;      /* lower limit of temperature scale */
        upper = 300;    /* upper limit */
        step = 20;      /* step size */

        fahr = lower;
        while (fahr <= upper) {
                celsius = (5.0/9.0) * (fahr-32.0);
                printf("%3.0f %6.1f\n", fahr, celsius);
                fahr = fahr + step;
        }

        return 0;
}

3.5 src/linecount.c

Count lines in input

download => linecount.c

#include <stdio.h>

/* count lines in input */

int main() {

  int c, nl;

  nl = 0;

  while ((c = getchar()) != EOF )
    if ( c == '\n')
      ++nl;

  printf("%d\n", nl);

  return 0;

}

3.6 src/exercise1_12.c

Write a program that prints its input one word per line

download => exercise1_12.c

/* Exercise 1-12  Write a program that prints its input one word per line  */
#include <stdio.h>
#include <stdlib.h>

#define INSIDE 1     /* inside a word  */
#define OUTSIDE 0    /* outside a word */

int main()
{
    int c;
    int state = OUTSIDE;
    while ( (c = getchar() ) != EOF ) {
        if ( c == ' ' || c == '\n' ) {
            if  (state == INSIDE) {
                putchar('\n');
            }
            state = OUTSIDE;
        } else {
            putchar(c);
            state = INSIDE;
        }
    }


}

3.7 src/countchars_2nd.c

download => countchars_2nd.c

/* count number of characters from standard input */
#include <stdio.h>  // printf , getchar
#include <stdlib.h> // exit_success

int main()
{
    double nc;

    for ( nc = 0; getchar() != EOF ; nc++)
        ;


    printf("%.0f\n", nc );

    exit( EXIT_SUCCESS );

}

3.8 src/exercise1_9.c

Write a program to copy its input to ints ouput, replacing each string of one or more blanks by a single blank

download => exercise1_9.c

/* Exercise 1.9  Write a program to copy its input to ints ouput, replacing each string of one or more blanks by a single blank  */

#include <stdio.h>
#include <stdlib.h> // exit_success

#define DEDUP_CHAR ' '

int main()
{
    int c;
    int last_found = 0;
    while (  (c = getchar()) != EOF )   {
        if ( c == DEDUP_CHAR ) {
            if ( last_found == 0 ) {
                putchar(c);
            }
            last_found = 1;
        } else {
            last_found = 0;
            putchar(c);
        }
    }

    return 0;
}

Example output:

cd source/acpg/ch1_all/ch1_autotools_new ; ./src/exercise1_9 < ./src/exercise1_9.c

#include <stdio.h>
#include <stdlib.h> // exit_success

#define DEDUP_CHAR ' '

int main()
{
 int c;
 int last_found = 0;
 while ( (c = getchar()) != EOF ) {
 if ( c == DEDUP_CHAR ) {
 if ( last_found == 0 ) {
 putchar(c);
 }
 last_found = 1;
 } else {
 last_found = 0;
 putchar(c);
 }
 }

 return 0;
}

3.9 src/longestline.c

Print longest input line

#include <stdlib.h>
#include <stdio.h>

#define MAXLINE 1000

/* print longest input line */

char line[MAXLINE];
char longest[MAXLINE];

void copy( char to[], char from[] );
int getline2( char line[], int maxsize );

int main() {

  int len, maxlength;
  maxlength = 0;

  while ( (len = getline2(line, MAXLINE )) > 0 ) {

    if ( len > maxlength ) {
      maxlength = len;
      copy( longest, line );

    }
  }

  if (maxlength > 0 )
    printf("%s", longest );

  return 0;
}

int getline2( char line[], int maxsize ) {

  int c, pos;
  pos = 0;
  while ( pos < maxsize-1 && ((c = getchar() ) != EOF) && c != '\n'  ) {
    line[pos] = c;
    pos++;
  }

  if ( c == '\n' ) {
    line[pos] = c;
    ++pos;
  }

  line[pos] = '\0';

  return pos;
}

void copy( char* to, char *from ) {

  while ( (*to++ = *from++) )
    ;

}

Example output

$ ./src/longestline   < src/longestline.c

  while ( pos < maxsize-1 && ((c = getchar() ) != EOF) && c != '\n'  ) {

3.10 src/testpow.c

Testing math library

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

#include <math.h>
#include <errno.h>


/* demo call by value */
int power( int base, int n ) {

  int p;
  for ( p = 1; n > 0; n-- ) {
    p *= base;
  }

  return p;
}


int main() {

  double x, y, result;

  x = -1;
  y = 0.5;

  /* raiz cuadrada de un numero negativo =  num complejo */

  result = pow( x, y );

  if ( errno == EDOM )
    printf(" numero complejo !!!");
  else
    printf("%.2f", result);


  printf( "power(2,5)=%d", power(2,5) );

  return 0;

}

Author: Sebastian Emilio Narvaez

Created: 2019-10-12 Sat 22:16

Emacs 25.2.2 (Org mode 8.2.10)

Validate