如何包含自己的一个函数
我写了一个iolib.c文件函数:
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <unistd.h>
4
5 ssize_t my_read(int fd, void *buffer, size_t length)
6 {
7 ssize_t done = length;
8
9 while(done > 0)
10 {
11 done = read(fd, buffer, length);
12
13 if(done != length)
14 if(errno == EINTR)
15 done = length;
16 else
17 {
18 perror("fail to read");
19 return -1;
20 }
21 else break;
22 }
23
24 return done;
25 }
26
27 ssize_t my_write(int fd, void *buffer, size_t length)
28 {
29 ssize_t done = length;
30
31 while(done > 0)
32 {
33 done = write(fd, buffer, length);
34
35 if(done != length)
36 if(errno == EINTR)
37 done = length;
38 else
39 {
40 perror("fail to write");
41 return -1;
42 }
43 else break;
44 }
45
46 return done;
47
48 }
又写了个iolib.h头文件
1 extern ssize_t my_read(int fd, void *buffer, size_t length);
2 extern ssize_t my_write(int fd, void *buffer, size_t length);
写了个socket程序:
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <netdb.h>
4 #include <arpa/inet.h>
5 #include <unistd.h>
6 #include <sys/socket.h>
7 #include <string.h>
8 #include <ctype.h>
9
10 #include "iolib.h"
11
12 #define MAX_LINE 100
13
14 void my_fun(char * p)
15 {
16 if(p == NULL)
17 return;
18
19 for(; *p != '\0'; p ++)
20 if(*p >= 'A' && *p <= 'Z')
21 *p = *p - 'A' + 'a';
22 }
23
24 int main(void)
25 {
26 struct sockaddr_in sin;
27 struct sockaddr_in cin;
28 int l_fd;
29 int c_fd;
30 socklen_t len;
31 char buf[MAX_LINE];
32 char addr_p[INET_ADDRSTRLEN];
33 int port = 8000;
34 int n;
35
36 bzero(&sin, sizeof(sin));
37 sin.sin_family = AF_INET;
38 sin.sin_addr.s_addr = INADDR_ANY;
39 sin.sin_port = htons(port);
40
41 if(l_fd = socket(AF_INET, SOCK_STREAM, 0) == -1)
42 {
43 perror("fail to create socket");
44 exit(1);
45 }
46
47 if(bind(l_fd, (struct sockaddr *)&sin, sizeof(sin)) == -1)
48 {
49 perror("fail to bind");
50 exit(1);
51 }
52
53 if(listen(l_fd,10) == -1)
54 {
55 perror("fail to listen");
56 exit(1);
57 }
58
59 printf("waiting ...\n");
60
61 while(1)
62 {
63 if(c_fd = accept(l_fd, (struct sockaddr *)&cin, &len) == -1)
64 {
65 perror("fail to accept");
66 exit(1);
67 }
68
69 n = read(c_fd, buf, MAX_LINE);
70 if(n == -1)
71 exit(1);
72 else if(n == 0)
73 {
74 printf("the connect has been closed\n");
75 close(c_fd);
76 continue;
77 }
78
79 inet_ntop(AF_INET, &cin.sin_addr, addr_p, sizeof(addr_p));
80
81 printf("client IP is %s, port is %d\n", addr_p, ntohs(cin.sin_port));
82
83 printf("client is : %s\n", buf);
84
85 my_fun(buf);
86
87 n = my_write(c_fd, buf, n);
88 if(n == -1)
89 exit(1);
90
91 if(close(c_fd) == -1)
92 {
93 perror("fail to close");
94 exit(1);
95 }
96
97 }
98
99 if(close(l_fd) == -1)
100 {
101 perror("fail to close");
102 exit(1);
103 }
104
105 return 0;
106
107 }
gcc server.c -o server却报错:
/tmp/ccL1YDaB.o: In function `main':
myserver.c:(.text+0x2a7): undefined reference to `my_write'
collect2: ld returned 1 exit status
请大家指教下是什么原因啊,谢谢!!
~