Programs and compilation to compile a program g

This preview shows page 69 - 83 out of 153 pages.

Programs and Compilation To compile a program: g++ <options> <source files> Recommended: g++ -Wall ansi o <executable_name> *.cpp -Wall show all warnings -ansi Strict ANSI compliance What’s an “executable”? In Windows, double-clicking on an icon runs a program E.g. double-click on C:\Windows\notepad.exe In Unix, you can run your executable from the command line! Type the executable name at the prompt, just like a command In fact, commands are actually executables However, you may need to specify the path to your executables ./<program> runs <program> in the current directory Example: ceylon:ehsu% g++ -Wall ansi o hello hello.cpp ceylon:ehsu% ./ hello
CS4315 A. Berrached::CMS::UHD 70 Example: Writing a C program on Unix Write a program that counts the number of non white-space characters in a text file. Program takes as command argument the name of the input file and displays the output on the standard output.
CS4315 A. Berrached::CMS::UHD 71 // Character Count: Basic Algorithm #include <stdio.h> #define BLANK ' ' #define NEWLINE '\n' int main(int argc, char *argv[]) { FILE *infile; char c; int char_count=0; // count the number of charecters in infile while ( (c = getc(infile)) != EOF) if ((c != BLANK) && (c != NEWLINE) ) ++char_count; printf("%d characters\n", char_count); return 0; }
CS4315 A. Berrached::CMS::UHD 72 Testing the # of command arguments if (argc !=2) { fprintf(stderr, " %s: expects 1 argument but was given %d\n", argv[0], argc-1); fprintf(stderr, "Usage: %s inputfile \n", argv[0]); exit(1); } int printf( char *format, arg1, arg2, ….) int fprintf( FILE * stream, char *format, arg1, arg2, ….)