Create A C program.
- Open a terminal (i used the pi user).
- Create and go to a directory for your C programs.
pi@raspberrypi ~ $ mkdir /home/pi/c
pi@raspberrypi ~ $ mkdir /home/pi/c/hello
pi@raspberrypi ~ $ cd /home/pi/c/hello
- Create and edit a c file.
pi@raspberrypi ~/c/hello $ nano hello.c
- Enter this small c program.
C Code:#include <stdio.h> int main() { printf("hello universe"); return 0; } - Exit and save.
- Compile and build the program. gcc = gnu compiler, -o = output filename
pi@raspberrypi ~/c/hello $ gcc -o hello hello.c
- Give execute rights.
pi@raspberrypi ~/c/hello $ chmod 755 hello
- Run the program.
pi@raspberrypi ~/c/hello $ ./hello
hello universe
Create a C program with headers and modules.
- Open and edit hello.c
pi@raspberrypi ~/c/hello $ nano hello.c
- Change the code to
C Code:#include "hello.h" #include <stdio.h> void hello() { printf("hello universe\n"); } - Create and edit hello.h
pi@raspberrypi ~/c/hello $ nano hello.h
- Enter this code. void hello() is a prototype for the hello function.
C Code:#ifndef __HELLO_H__ #define __HELLO_H__ void hello(); #endif
- Create and edit main.c
pi@raspberrypi ~/c/hello $ nano main.c
- Enter this code.
C Code:#include "hello.h" int main(){ hello(); return 0; } - Compile and build the program. gcc = gnu compiler, -o = output filename
pi@raspberrypi ~/c/hello $ gcc -o hello hello.c main.c
- Give execute rights
pi@raspberrypi ~/c/hello $ chmod 755 hello
- Run the program
pi@raspberrypi ~/c/hello $ ./hello
hello universe
Create a C++ program with headers and modules.
- Create a directory for the cpp files
pi@raspberrypi ~/c/hello $ mkdir /home/pi/cpp
pi@raspberrypi ~/c/hello $ mkdir /home/pi/cpp/hello
pi@raspberrypi ~/c/hello $ cd /home/pi/cpp/hello
- Create and edit hello.h
pi@raspberrypi ~/cpp/hello $ nano hello.h
- Enter this code.
C Code:#ifndef __CHELLO_H__ #define __CHELLO_H__ class CHello { public: CHello(); ~CHello(); void SayHello(); }; #endif - Create and edit hello.cpp
pi@raspberrypi ~/cpp/hello $ nano hello.cpp
- Enter this code (for VB users, note that the class member methods are defined outside the class defenition. Inside is possible too.)
C Code:#include <iostream> #include "hello.h" // constructor CHello::CHello(){ std::cout << "constructor\n"; } // destructor CHello::~CHello(){ std::cout << "destructor\n"; } // member method void CHello::SayHello(){ std::cout << "hello universe\n"; } - Create and edit main.cpp
pi@raspberrypi ~/cpp/hello $ nano main.cpp
- Enter this code
C Code:#include "hello.h" int main(){ CHello * pHello = new CHello(); pHello->SayHello(); delete pHello; return 0; } - Compile the files and build the program. gcc = gnu compiler, -lstdc++ = standard C++ flag, -o = output filename
pi@raspberrypi ~/cpp/hello $ gcc -lstdc++ -o hello hello.cpp main.cpp
- Give hello execute rights
pi@raspberrypi ~/cpp/hello $ chmod 755 hello
- Run the program.
pi@raspberrypi ~/cpp/hello $ ./hello
constructor
hello universe
destructor


Inzender



