exercise 1: Compiling C programs
Your have to write four files, a makefile, two c programs and a c header file. (Refer to A.3)
The mylib.c should implement a function named transpose() which will transpose the input string in place, that is, lowercase to uppercase or uppercase to lowercase. Its prototype is put in mylib.h and the prototype is:
void transpose(char *s);
The main() in main.c should call the transpose() on each argument and print them out.
For example:
$ ls
Makefile main.c mylib.c mylib.h
$ make
cc -c -o main.o main.c
cc -c -o mylib.o mylib.c
gcc -o trans main.o mylib.o
$ make
make: 'trans' is up to date.
$ touch mylib.c
$ make
cc -c -o mylib.o mylib.c
gcc -o trans main.o mylib.o
$ touch main.c
$ make
cc -c -o main.o main.c
gcc -o trans main.o mylib.o
$ make
make: 'trans' is up to date.
$ ls
Makefile main.c main.o mylib.c mylib.h mylib.o trans*
$
$ ./trans Klim is 300@moon
kLIM
IS
300@MOON
$
解答:
//-----main.c-----
#include <stdio.h>
#include "mylib.h"
int main(int argc, char *argv[]) {
int i;
for (i = 1; i < argc; i++) {
transpose(argv[i]);
printf ("%s\n", argv[i]);
}
}
//-----mylib.c-----
#include <stdio.h>
#include <string.h>
#include "mylib.h"
void transpose(char *s) {
int i = 0;
while (s[i] != '\0') {
if ((s[i] >= 'A' && s[i] <= 'Z') ||
(s[i] >= 'a' && s[i] <= 'z')) {
s[i] = (s[i] >= 'A' && s[i] <= 'Z') ?
s[i] + ('a' - 'A') :
s[i] - ('a' - 'A') ;
}
i++;
}
}
//-----mylib.h-----
void transpose(char *s);
//-----Makefile-----
trans: main.o mylib.o gcc -o trans main.o mylib.o main.o: main.c gcc -c main.c mylib.o: mylib.c gcc -c mylib.c clean: rm *.o trans
執行結果:
沒有留言:
張貼留言