gcc與 g++
在 LInux Ubuntu 要如何 Complie C (使用 gcc)或者是 C++ 檔案(使用 g++)
gcc 的用法相當地多,只要先記住以下這行用法
1 gcc –o output_file_name source.c
如果沒有加”-o output_file_name”這個選項的話,預設輸出會是 a.out
一般的 C 副檔名可以取名為 .c
如 hello_c.c
1 #include <stdio.h>
2
3 int main() {
4
5 printf("%s","Hello World!!");
6
7 }
2
3 int main() {
4
5 printf("%s","Hello World!!");
6
7 }
在 console 下打
1 gcc -o hello_c hello.c
會出現一些錯誤 , 例如找不到 stdio.h
利用 sudo find / -name stdio.h 尋找也會找不到檔案
因此需要下載 sudo apt-get install g++
另外一個範例為 c++
hello_cc.cc
1 #include <iostream>
2
3 using namespace std;
4
5 int main(int argc,char *argv[])
6
7 {
8
9 cout << "Hello, world!\n";
10
11 return 0;
12
13 }
2
3 using namespace std;
4
5 int main(int argc,char *argv[])
6
7 {
8
9 cout << "Hello, world!\n";
10
11 return 0;
12
13 }
c++ 則要使用 g++ 來 complie
1 $ g++ hello_cc.cc -o hello
或是分成兩行
1 $ g++ -Wall -c hello.cc
2 $ g++ hello.o (should use g++)
2 $ g++ hello.o (should use g++)
一個完整的範例包含 Makefile
1 main.cc
2
3 #include <iostream>
4
5 using namespace std;
6
7 // Output in print.cc
8
9 extern void Output(void);
10
11 int main(void)
12
13 {
14
15 Output();
16
17 return 0;
18
19 }
20
21
22
23 print.cc
24
25 #include <iostream>
26
27 using namespace std;
28
29 void Output(void)
30
31 {
32
33 cout << "print one line!" << endl;
34
35 }
36
37
38
39 Makefile
40
41 # Makefile for printline
42
43 #
44
45 # GNU g++
46
47 #
48
49 # use gcc here for usual C Code
50
51 CC = g++
52
53 # Put the parameters for compiling the c code here
54
55 # ( -O2 is a kind of Optimization parameter )
56
57 CFLAGS = -O2
58
59 # Object Files
60
61 # ( make will automatically search the corresponding .c or .cc file for
62
63 # compiling )
64
65 OBJ = main.o print.o
66
67 all: printline
68
69 clean:
70
71 rm -f *.o core printline
72
73 printline: $(OBJ)
74
75 $(CC) $(CFLAGS) -o printline $(OBJ)
2
3 #include <iostream>
4
5 using namespace std;
6
7 // Output in print.cc
8
9 extern void Output(void);
10
11 int main(void)
12
13 {
14
15 Output();
16
17 return 0;
18
19 }
20
21
22
23 print.cc
24
25 #include <iostream>
26
27 using namespace std;
28
29 void Output(void)
30
31 {
32
33 cout << "print one line!" << endl;
34
35 }
36
37
38
39 Makefile
40
41 # Makefile for printline
42
43 #
44
45 # GNU g++
46
47 #
48
49 # use gcc here for usual C Code
50
51 CC = g++
52
53 # Put the parameters for compiling the c code here
54
55 # ( -O2 is a kind of Optimization parameter )
56
57 CFLAGS = -O2
58
59 # Object Files
60
61 # ( make will automatically search the corresponding .c or .cc file for
62
63 # compiling )
64
65 OBJ = main.o print.o
66
67 all: printline
68
69 clean:
70
71 rm -f *.o core printline
72
73 printline: $(OBJ)
74
75 $(CC) $(CFLAGS) -o printline $(OBJ)