Understanding Portable Programming in C/C++: Standards and Best Practices

miscellaneous unix c concepts n.w
1 / 32
Embed
Share

Explore key concepts of portable programming in C/C++, including standards, compiler options, and debugging techniques. Learn how to ensure code portability across different platforms and enhance your skills in writing efficient and portable C/C++ programs.

  • C/C++ programming
  • Portable programs
  • Compiler standards
  • Debugging techniques
  • Coding conventions

Uploaded on | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Miscellaneous UNIX/C Concepts UNIX environment C standards and portable C program C compilers Debugger Make Some commonly used C/C++ programming tricks and conventions. The system function Key based authentication Run commands on a remote machine Readings APUE 7.4, 7.5, 7.9, 8.13 1

  2. Portable C/C++ programs and C/C++ standards Portable programs run on different platforms. Most C/C++ compilers by default support ANSI C/C++ plus extensions. The extensions kill the portability. Example non-standard constructs: typeof(var), ({a=1; b=2;}), see example0.c. Keys for writing portable programs Following language standard (e.g using ANSI C/C++). Knowing which language extensions are used. 2

  3. Portable C/C++ programs and C/C++ standards C standards: Original ANSI C of 1989: ANSI/ISO/IEC 9899:1990 ANSI/ISO/IEC 9899:1995 ISO/IEC 9899:1999 ISO9899:2011 C++ standards: Original ANSI C++ of 1998: ANSI/ISO/IEC 14882: 1998 ISO/IEC 14882: 2003 ISO/IEC 14882: 2011 ISO/IEC 14882: 2014 ISO/IEC 14882: 2017 ISO/IEC 14882: 2020 C/C++ compiler can enforce the standard used 3

  4. C/C++ Compilers gcc/g++, cc Using ANSI C/C++, the code must pass Wall ansi pedantic or -Wall std=xxx pedantic with no warning/error messages -ansi : ISO C90 programs (-std=C90) or C++98 (-std=c++98) -ansi + -pedantic : reject non-ISO programs -std=c99 : ISO C99 program -std=c11 : ISO C11 program -std=c++11 : C++ 2011 program man gcc for more information. Writing portable programs requires clear identification of the C/C++ dialect that is used. All programs in this course must be compiled with -Wall ansi pedantic or -Wall std=xxx pedantic with no warning/error unless you know a specific reason to not use such flags. 4

  5. C Compilers (Contd) See the example code (example1.c), how to fix the errors/warnings? Some examples: gcc g c Wall ansi pedentic example.c gcc Wall ansi pedantic example1.c example2.c gcc g example.o gcc g example.o -lm 5

  6. Debugger on linprog Debugging in an IDE is usually easy. Debugging on the server with no IDE can be hard. Debuggers on linprog include gdb, ddd, etc. The code must be compiled with g option. The debugger functionality (gdb): Finding the line that causes coredump. See example: Break point/show value/change value/step/next/continue/print Very efficient in debugging sequential code Not very effective in debugging concurrent code (multiple threads, multiple processes) 6

  7. Core dump File A file containing memory image of process when it terminates (crashes) A common reason of core dump file not created is resource limit on core file Controlling core file size is shell specific csh: limit [resource] [limit], or simply unlimit to remove all limits Where resource should be coredumpsize sh: ulimit -c [limit] Load core dump file into debugger gdb: gdb executable_file coredump_file ddd: ddd executable_file coredump_file 7

  8. Make A tool to update files that are derived from other files. Great for software development. Discussions based on GNU make utility make command make [-f makefile][option][target] The default files for make are GNUmakefile, makefile, Makefile, in that order GNUmakefile is not recommended Makefile is recommended The default files can be overwritten with the f option make f myprog.mk 8

  9. Make A makefile has five kinds of components: Explicit rules: tell when and how to remake one or more files (targets) Implicit rules: tell when and how to remake a class of files Variable definitions: define a text string for a variable Directives: tell to do something special when reading a make file Comments: anything after a # sign 9

  10. Make Variable definitions: String1 = string2 E.g. CC=gcc CFLAG=-Wall ansi pedantic Default variables (default value) CC: default C compiler (cc) CXX: default C++ compiler (g++) CFLAGS: extra flags to give to C compiler (empty) CXXFLAGS: extra flags to give to C++ compiler (empty) CPPFLAGS and LDFLAGS (empty) 10

  11. Make Explicit rules: Target [target ] : [prerequisite ] <tab> command <tab> command Example (see makefile1): a.out : myprog1.c myprog2.c myprog3.c $(CC) myprog1.c myprog2.c myprog3.c Target and prerequisite by default are files. When we type make Target , the make program would look for the rule to make Target and try to compare the time stamp of each of the prerequisites to the time stamp of Target, if the time stamp of a prerequisite is newer, the list of commands will be executed. If make does not specify a target, the default is the first target in the makefile 11

  12. Make Explicit rules: Target [target ] : [prerequisite ] <tab> command <tab> command Example (see makefile): a.out : myprog1.o myprog2.o myprog3.o $(CC) myprog1.o myprog2.o myprog3.o If there are rules to make a prerequisite, the make program will first apply this process recursively to the prerequisite (post- order traversal of the prerequisite tree). If the target does not exist, the commands always run making a target such that running the commands does not create the target file (see make clean in makefile). 12

  13. Make Implicit rules: Tell make how to use certain customary techniques to remake a target so that you do not have to supply the rules For example, look at the following makefile foo : foo.o bar.o cc -o foo foo.o bar.o $(CFLAGS) $(LDFLAGS) make will search an implicit rule to make foo.o and bar.o since we did not specify how to make them Define new implicit rules by writing pattern rules Similar to explicit rule, except target contains % % is a pattern that matches any string Example %.o : %.c $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ % : %.c 13 $(CC) $(CFLAGS) $(CPPFLAGS) $< -o $@

  14. Make Automatic variables $@: target file $<: name of first prerequisite $?: name of all prerequisites newer than target $^: name of all prerequisites %.o : %.c $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ % : %.c $(CC) $(CFLAGS) $(CPPFLAGS) $< -o $@ 14

  15. Make Implicit rules vs explicit rules: Use the same rule for many files. This results in the same dependence pattern to be applied. This is often undesired. Avoid implicit rules if possible. %.o : %.c $(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@ % : %.c $(CC) $(CFLAGS) $(CPPFLAGS) $< -o $@ 15

  16. Make See the example makefile2 How to modify the makefile if I want only recompile one file instead of the whole system? A file (makefile5) with pattern rules What happens when we do make a.o ? What about make b.o ? What happens when we do make myprog1.o ? What happens when myprog2.o also depends on myprog.h? When multiple rules match the target, explicit rules have higher priority over pattern rules More info GNU make 16

  17. Some C programming tricks: Header files: contain common declarations. Source files use the #include directive to include the header files. Sometimes using header files can cause problems, see example2.c. Including a header file multiple times may cause duplicate declaration errors. Why including stdio.h two times does not have any problem? Look at /usr/include/stdio.h, this file is protected and will never be included in any file two times. 17

  18. Some C programming tricks: Header files: The following mechanism prevents the body of a header file from being included multiple times under any situation. All system .h files are protected this way, and you should protect your .h files as well! #ifndef MYHEADER #define MYHEADER . /* the body of the header file */ #endif Each header file must use a different MYHEADER variable. 18

  19. Some C programming tricks: How/when is a macro processed? Try gcc E example1a.c and cpp example1a.c #define MAX_LENGTH 256 For (I=0; I<MAX_LENGTH; I++) . 19

  20. Some C programming tricks: Macros with parameters are not the same as functions: Macros with parameters look/work like functions: #define max(a, b) (a>b)?a:b Macros with parameters need to be defined carefully, otherwise weird things can happen. What is wrong with the following macro? #define sum(a, b) a+b 20

  21. Some C programming tricks: What is wrong with the following macro? #define sum(a, b) a +b Checkout example3.c How to fix the problem? 21

  22. UNIX convention Question: When you write your main function in a C/C++ program, what is the return value of the main function? 22

  23. UNIX Convention Normal execution: exit code 0 This is the default exit code. This is achieved by calling exit(0) or return 0 in the main function. Abnormal execution: exit with a non-zero code UNIX utility programs like make use the exit code. Try to follow this convention in this course, or some utility may break. See example x.mk Make checks exist status of each command, and gives up when error occurs. All UNIX utilities do the similar thing. You can use i option to ignore errors make i f x.mk More portable EXIT_SUCCESS, and EXIT_FAILURE 23

  24. C/C++ Programs with command line arguments int main(int argc, char* argv[]) {} argc is the count of command line arguments. argc >=1. Command line arguments are separated by spaces. argv is an array of pointers to character strings that contain the actual command-line arguments. See example4.c for the use of command line arguments. You will need to use command line arguments in most of the programming assignments. 24

  25. The Environment List Try command env Environment variables can be defined in shell setenv DISPLAY L103:0.0 -- tcsh export DISPLAY=L103:0.0 -- bash These variables can be accessed in the program extern char **environ; 25

  26. Environment List This figure shows an example how the environment list is organized. See example6.c for how to use environ. 26

  27. Environment List ANSI C also specifies a routine for accessing environment variables: char *getenv(char *name) See example7.c. Other routines (not in ANSI, now in some POSIX): int putenv(const char *str); int setenv (const char *name, const char *value, int rewrite); void unsetenv (const char *name); See example8.c You can use environment variables to direct the program execution. See example8a.c. Try setenv GROUPSIZE 8; setenv MYID 0; ./a.out setenv GROUPSIZE 8; setenv MYID 1; ./a.out 27

  28. Some routines to parse/format strings in C sprintf/sscanf sprintf(str, format, arg1, arg2 .) Similar to printf except that the result is stored in str. sscanf(str, format, arg1, arg2, ) Similar to scanf except that the values are read from str. Example: How to get all the fields from the output of ps on linprog? See example5.c for the use of sprintf/sscanf 28

  29. The system Function Allows commands to be executed in a program int system(const char *string) Works as if string is typed in a terminal. Return value is a wait status of the exit status (format specified by waitpid()) if successful. Use WEXITSTATUS() to retrieve the status If error return -1 or 127. See example5a.c, and example5c.c 29

  30. ssh with Key based authentication Password based authentication is inconvenient at times Remote system management Starting a remote program Key based authentication allows login without typing the password. Key based authentication with ssh in UNIX Remote ssh from machine A to machine B Step 1: at machine A: ssh-keygen t rsa (do not enter any pass phrase, just keep typing enter ) Step 2: append A:.ssh/id_rsa.pub to B:.ssh/authorized_keys More information, SSH with Keys HOWTO at http://sshkeychain.sourceforge.net/mirrors/SSH-with- Keys-HOWTO/SSH-with-Keys-HOWTO.html

  31. Run command remotely using ssh On linprog1, try ssh linprog2 who Put the executable (ex8a) for example8a.c in home directory. Run the following: ssh linprog3 setenv GROUPSIZE 8; setenv MYID 0; ./ex8a ssh linprog4 setenv GROUPSIZE 8; setenv MYID 1; ./ex8a 31

  32. Other commands you may need for assignment ssh qx linprog2 mkdir cop5570assignment1tmp ssh qx linprog2 rm r f cop5570assignment1tmp scp q proj1.pdf xyuan@linprog2:. ssh -qx linprog2 cd cop5560assignment1tmp; setenv MYGROUP 5; gcc test.c; ./a.out ssh qx linprog2 pkill sleep 32

More Related Content