Tag: c

  • Chapter 9: Bitwise Operations for Advanced Nerds

    Today’s post is a preview of chapter 9 in my upcoming book on programming in DOS. If anything, this chapter is more of a joke or a meme than actually useful for writing most programs. I was feeling naughty and decided to show how far down the coding rabbit hole I have traveled!

    This chapter contains information which will assist you in understanding more about how computers work, but that in general is not required for MOST programming unless you are trying to operate on individual bits.

    To start out, I will describe 5 essential bitwise operations independently of any specific programming language. This is because these operations exist in every programming language I know of, including Assembly and C.

    After I have explained what the bitwise operations do, I will give examples of how this can be used in Assembly language to substitute for addition and subtraction! You might wonder why you would do this, the fact is that you don’t need to but it is a fun trick that only advanced nerds like me do for a special challenge.

    The Bitwise Operations

    This chapter explains 5 bitwise operations which operate on the bits of data in a computer. For the purpose of demonstration, it doesn’t matter which number the bits represent at the moment. This is because the bits don’t have to represent numbers at all but can represent anything described in two states. Bits are commonly used to represent statements that are true or false. For the purposes of this section, the words AND, OR, XOR are in capital letters because their meaning is only loosely related to the English words they get their name from.

    Bitwise AND Operation

    0 AND 0 == 0
    0 AND 1 == 0	
    1 AND 0 == 0
    1 AND 1 == 1
    

    Think of the bitwise AND operation as multiplication of single bits. 1 times 1 is always 1 but 0 times anything is always 0. That’s how I personally think of it. I guess you could say that something is true only if two conditions are true. For example, if I go to Walmart AND do my job then it is true that I get paid.

    I like to think of the AND operation as the “prefer 0” operation. It will always choose a 0 if either of the two bits is a 0, otherwise, if no 0 is available, it will choose 1.

    Bitwise OR Operation

    0 OR 0 == 0
    0 OR 1 == 1	
    1 OR 0 == 1
    1 OR 1 == 1
    

    The bitwise OR operation can be thought of as something that is true if one or two conditions are true. For example, it is true that playing in the street will result in you dying because you got run over by a car. It is also true that if you live long enough, something else will kill you. Therefore, the bit of your impending death is always 1.

    I like to think of the OR operation as the “prefer 1” operation. It will always choose a 1 if one of the two bits is a 1, otherwise, if no 1 is available, it will choose 0.

    Bitwise XOR Operation

    0 XOR 0 == 0
    0 XOR 1 == 1	
    1 XOR 0 == 1
    1 XOR 1 == 0
    

    The bitwise XOR operation is different because it isn’t really used much for evaluating true or false. Instead, this operation returns 1 if the bits compared are different or 0 if they are the same. This means that any bit, or group of bits, XORed with itself, will always result in 0.

    If you look at my XOR chart above, you will see that using XOR of any bit with a 1 causes the result to be the opposite of the original bit.

    The XOR operation is the quickest way to achieve this bit inversion. If you have a setting that you want to switch on or off, you can toggle it by XORing that bit with 1.

    While the AND, OR, XOR operations can work in the context of individual bits, or groups of them, the next operations, the bit shifts, only make sense in the context of a group of bits. At minimum, you will be operating on 8 bits at a time because a byte is the lowest addressable size of memory.

    Bitwise Left and Right Shift Operations

    Consider the case of the following 8 bit binary value:

    00001000

    This would of course represent the number 8 because a 1 is in the 8’s place value. We can left shift or right shift.

    00001000 ==  8 : is the original byte
    
    00010000 == 16 : original left shift 1
    00000100 ==  4 : original right shift 1
    

    That is really all there is to shifts. They can be used to multiply or divide by a power of two. In some cases, this can be faster than using the mul and div instructions described in chapter 4.

    Example 0: Fake Add

    The following example shows how it is possible to write an addition routine using a combination of the AND,XOR,SHL operations. In this case, the numbers are shown in decimal to be easier for most people to see that the addition is correct.

    org 100h
    
    main:
    
    mov word [radix],10 ; choose radix for integer input/output
    mov word [int_width],1
    
    mov di,1987
    mov si,38
    
    mov ax,di
    call putint
    mov ax,si
    call putint
    call putline
    
    fake_add:
    mov ax,di
    xor di,si
    and si,ax
    shl si,1
    jnz fake_add
    
    mov ax,di
    call putint
    mov ax,si
    call putint
    
    mov ax,4C00h
    int 21h
    
    include 'chastelib16.asm'
    

    If you run it, you will see that the correct result of 2025 which is 1987+38. These are the values we set the di and si registers to before simulating addition with these fancy bitwise operations that make even seasoned programmers run scared.

    But how does this monstrosity of a program work? You see the AND operation keeps track of whether both bits in each place value are 1 or not. If they both are, this means that we have to “carry” those bits as we would do in an ordinary binary division. We store the carry in the si register and then left shift it once each time in the loop. The loop continues until si equals zero and there are no more bits to invert with XOR.

    The fact that it works is easy to work out in my head but I don’t blame you if you can’t visualize it. However, this shows the power of what bit operations can do, even though you will probably never need to do this.

    Example 1: Fake Sub

    In case the fake addition example above wasn’t enough for you, here is a slightly modified example that does a fake subtraction operation using the same operations. Try it out and you will see that it subtracts 38 from 2025 and gets the original 1987.

    org 100h
    
    main:
    
    mov word [radix],10 ; choose radix for integer input/output
    mov word [int_width],1
    
    mov di,2025
    mov si,38
    
    mov ax,di
    call putint
    mov ax,si
    call putint
    call putline
    
    fake_sub:
    xor di,si
    and si,di
    shl si,1
    jnz fake_sub
    
    mov ax,di
    call putint
    mov ax,si
    call putint
    
    mov ax,4C00h
    int 21h
    
    include 'chastelib16.asm'
    

    I will try to explain how this works. You see, we first XOR the di register with the si register. Then, we AND si with the new value of di. This means that the bits in the current place value will only both be 1 if those bits were 0 in di and then were inverted to 1 by the XOR with si. This means that at the start of the loop, destination bit=0 and source bit=1. 0 minus 1 means that we need to “borrow” (I hate that term because it is really stealing because we never give it back). We left shift si as usual and then we keep XORing the new borrow in si until it is zero.

    Also, you may have noticed that I never used the “cmp” instruction to compare si with zero in this examples. This is because the zero flag is automatically updated with most operations. In fact there are places in my standard library of functions (chastelib) where it wasn’t strictly required to compare with “cmp” but I added it for clarity so I could read my code and more easily remember what I was doing.

    But let’s face it, the examples in this chapter are purely for showing off how advanced my knowledge of the binary numeral system and manipulating bits in ways no reasonable person should ever attempt. I must admit, it would be great for an obfuscated code contest to make a program with code that is unreadable to most humans.

  • Chastity Windows Reverse Engineering Notes

    The Windows version of FASM includes header files for the Windows API. It also includes some examples, but not a single one of them were a simple “Hello World” console program.

    Fortunately, I was able to find one that actually assembled and ran on the FASM forum. Below is the source code.

    format PE console
    include 'win32ax.inc'
    .code
    start:
    invoke  WriteConsole, <invoke GetStdHandle,STD_OUTPUT_HANDLE>,"Hello World!",12,0
    invoke  ExitProcess,0
    .end start
    

    To get it working required me to keep the include files in a location I remembered and set the include environment variable. I found this out from the FASM Windows documentation.

    set include=C:\fasm\INCLUDE

    However, there was another problem. The example that I found online and got working uses macros, most specifically, one called “invoke”. While this works if you include the headers, it hides the details of what is actually happening. Therefore, I decided to reverse engineer the process by using NOP instructions to sandwich the bytes of machine code.

    90 hex is the byte for NOP (No OPeration). So to extract the macro call that exits the program, I use this.

    db 10h dup 90h
    invoke  ExitProcess,0
    db 10h dup 90h
    

    Then I disassemble the executable and find the actual instructions given.

    ndisasm main.exe -b 32 > disasm.txt

    As simple as this method is, it actually works. For example, this output is given as part of the output.

    0000022D  90                nop
    0000022E  90                nop
    0000022F  90                nop
    00000230  90                nop
    00000231  90                nop
    00000232  90                nop
    00000233  90                nop
    00000234  90                nop
    00000235  90                nop
    00000236  90                nop
    00000237  90                nop
    00000238  90                nop
    00000239  90                nop
    0000023A  90                nop
    0000023B  90                nop
    0000023C  90                nop
    0000023D  6A00              push dword 0x0
    0000023F  FF1548204000      call dword near [0x402048]
    00000245  90                nop
    00000246  90                nop
    00000247  90                nop
    00000248  90                nop
    00000249  90                nop
    0000024A  90                nop
    0000024B  90                nop
    0000024C  90                nop
    0000024D  90                nop
    0000024E  90                nop
    0000024F  90                nop
    00000250  90                nop
    00000251  90                nop
    00000252  90                nop
    00000253  90                nop
    00000254  90                nop
    

    There can be no mistake that it is that location between the NOPs where the relevant code is. Therefore, I replaced the macro that exits the program with this.

    ;Exit the process with code 0
     push 0
     call [ExitProcess]
    

    What I learned

    As I repeated the same process for the other macros, I found that the way system calls in Windows work is that the numbers are pushed onto the stack in the reverse order they are needed. I was able to decode the macros and get a working program without the use of “invoke”. Here is the full source!

    format PE console
    include 'win32ax.inc'
    
    main:
    
    ;Write 13 bytes from a string to standard output
    push 0              ;this must be zero. I have no idea why!  
    push 13             ;number of bytes to write
    push main_string    ;address of string to print
    push -11            ;STD_OUTPUT_HANDLE = Negative Eleven
    call [GetStdHandle] ;use the above handle
    push eax            ;eax is return value of previous function
    call [WriteConsole] ;all the data is in place, do the write thing!
    
    ;Exit the process with code 0
    push 0
    call [ExitProcess]
    
    .end main
    
    main_string db 'Hello World!',0Ah
    

    I don’t know much about the Windows API, but I did discover some helpful information when I searched the names of these functions that were part of the original macros.

    https://learn.microsoft.com/en-us/windows/console/getstdhandle
    https://learn.microsoft.com/en-us/windows/console/writeconsole

    Why I did this

    You might wonder why I even bothered to get a working Windows API program in Assembly Language. After all, I am a Linux user to the extreme. However, since Windows is the most used operating system for the average person, I figured that if I write any useful programs in Assembly for 32-bit Linux, I can probably port them over to Windows by changing just a few things.

    Since my toy programs are designed to write text to the console anyway and I don’t do GUI stuff unless I am programming a game in C with SDL, I now have enough information from this small Hello World example to theoretically write anything to the console that I might want to in an official Windows executable.

    Obviously I need to learn a lot more for bigger programs but this is the first Assembly program I have ever gotten working for Windows, despite my great success with DOS and Linux, which are easier because they are better documented and ARE TAUGHT BETTER by others. People programming Assembly in Windows have been ruined by macros which hide the actual instructions being used. As I learn how these things work, I will be sure to pass on the information to others!

  • chastehex-DOS-32-bit

    This is a video showing some very long source code of a DOS program I wrote using Assembly Language.

    This program is technically a 16 bit DOS .com program and yet it can access 32 bit addresses of the file it operates on because the LSEEK DOS call uses CX:DX as a 32 bit address by using two 16 bit registers. By modifying several parts of the program, I improved upon it greatly. It should theoretically be able to operate on any file less than 2 gigabytes even though the program itself never accesses more than 16 bytes at one time.

    I may have just invented the world’s smallest and fastest DOS hex dumper and editor. The official gitlab repository has the source code seen in this video as well as the Linux 32 bit Assembly and the original C version I wrote first when I invented this program.

    https://gitlab.com/chastitywhiterose/chastehex.git

    I will have to make more videos showing examples of how it can be used, but I have a readme file in the repository that explains what it does and why I made it.

    ——–D-2142——————————-
    INT 21 – DOS 2+ – “LSEEK” – SET CURRENT FILE POSITION
    AH = 42h
    AL = origin of move
    00h start of file
    01h current file position
    02h end of file
    BX = file handle
    CX:DX = (signed) offset from origin of new file position
    Return: CF clear if successful
    DX:AX = new file position in bytes from start of file
    CF set on error
    AX = error code (01h,06h) (see #01680 at AH=59h/BX=0000h)
    Notes: for origins 01h and 02h, the pointer may be positioned before the
    start of the file; no error is returned in that case (except under
    Windows NT), but subsequent attempts at I/O will produce errors
    if the new position is beyond the current end of file, the file will
    be extended by the next write (see AH=40h); for FAT32 drives, the
    file must have been opened with AX=6C00h with the “extended size”
    flag in order to expand the file beyond 2GB
    BUG: using this method to grow a file from zero bytes to a very large size
    can corrupt the FAT in some versions of DOS; the file should first
    be grown from zero to one byte and then to the desired large size
    SeeAlso: AH=24h,INT 2F/AX=1228h

  • DOS Assembly putstring function

    This is a small program which uses the putstring function I wrote. This function is one of 4 ultimate functions I have created which make up “chastelib”. DOS programming is simpler than Windows and is not that different from Linux in that system calls are done with an interrupt.

    org 100h
    
    main:
    
    mov ax,text
    call putstring
    
    mov ax,4C00h
    int 21h
    
    text db 'Hello World!',0Dh,0Ah,0
    
    ;This section is for the putstring function I wrote.
    ;It will print any zero terminated string that register ax points to
    
    stdout dw 1 ; variable for standard output so that it can theoretically be redirected
    
    putstring:
    
    push ax
    push bx
    push cx
    push dx
    
    mov bx,ax                  ;copy ax to bx for use as index register
    
    putstring_strlen_start:    ;this loop finds the length of the string as part of the putstring function
    
    cmp [bx], byte 0           ;compare this byte with 0
    jz putstring_strlen_end    ;if comparison was zero, jump to loop end because we have found the length
    inc bx                     ;increment bx (add 1)
    jmp putstring_strlen_start ;jump to the start of the loop and keep trying until we find a zero
    
    putstring_strlen_end:
    
    sub bx,ax                  ; sub ax from bx to get the difference for number of bytes
    mov cx,bx                  ; mov bx to cx
    mov dx,ax                  ; dx will have address of string to write
    
    mov ah,40h                 ; select DOS function 40h write 
    mov bx,[stdout]            ; file handle 1=stdout
    int 21h                    ; call the DOS kernel
    
    pop dx
    pop cx
    pop bx
    pop ax
    
    ret
    

    Anyone can assemble and run this source code, but you will need a DOS emulator like DOSBox in order for it to work. In fact, I have a video showing me assembling and running it inside of DOSBox.

    Lately I have been having a programming phase and am working on a book about programming in DOS. There is no money involved in this because nobody except nerds like me care about DOS. Speaking of nerds, if you follow my blog, don’t forget that this site was set up for teaching Chess. Leave me a comment if you play Chess online or live in Lee’s Summit. I am still playing Chess every day although some of my time has been taken up with programming in Assembly language because it is so much fun.

    If you like this post, you may be interested in my much longer post/book that is all about Assembly programming in DOS.

  • Chastity’s Hex Compare Tool

    Welcome to Chastity’s Hex Compare program also known as “chastecmp”. Enter two filenames as command line arguments such as:

    ./chastecmp file1.txt file2.txt

    It works for any binary files too, not just text. In fact for text comparison you want entirely different tools. This tool can be used to find the tiny differences between files in hexadecimal. It shows only those bytes which are different. I wrote it as a solution to a reddit user who asked how to compare two files in hexadecimal.

    It is an improvement over the Linux “cmp” tool which displays the offsets in decimal and the bytes in octal. Aside from using two different bases in the data, it falls short of usefulness because there are more hex editors than octal editors.

    Here are also some graphical tools I can recommend if you are looking for a GUI instead of my command line program.

    vbindiff
    wxHexeditor

    Below is the full source code:

    #include <stdio.h>
    #include <stdlib.h>
     
    int main(int argc, char *argv[])
    {
     int argx,x;
     FILE* fp[3]; /*file pointers*/
     int c1,c2;
     long flength[3]; /*length of the file opened*/
       
     /*printf("argc=%i\n",argc);*/
    
     if(argc<3)
     {
      printf("Welcome to Chastity's Hex Compare program also known as \"chastecmp\".\n\n");
      printf("Enter two filenames as command line arguments such as:\n");
      printf("%s file1.txt file2.txt\n",argv[0]);
      return 0;
     }
    
     argx=1;
     while(argx<3)
     {
       fp[argx] = fopen(argv[argx], "rb"); /*Try to open the file.*/
       if(!fp[argx]) /*If the pointer is NULL then this becomes true and the file open has failed!*/
       {
        printf("Error: Cannot open file \"%s\": ",argv[argx]);
        printf("No such file or directory\n");
        return 1;
       }
      /*printf("File \"%s\": opened.\n",argv[argx]);*/
    
      printf("fp[%X] = fopen(%s, \"rb\");\n",argx,argv[argx]);
      argx++;
     }
    
     printf("Comparing files %s and %s\n",argv[1],argv[2]);
    
     argx=1;
     while(argx<3)
     {
      fseek(fp[argx],0,SEEK_END); /*go to end of file*/
      flength[argx]=ftell(fp[argx]); /*get position of the file*/
      printf("length of file fp[%X]=%lX\n",argx,flength[argx]);
      fseek(fp[argx],0,SEEK_SET); /*go back to the beginning*/
      argx++;
     }
    
     x=0;
     while(x<flength[1])
     {
      c1 = fgetc(fp[1]);
      c2 = fgetc(fp[2]);
      if(c1!=c2)
      {
       printf("%08X: %02X %02X\n",x,c1,c2);
      }
      x++;  
     }
    
     argx=1;
     while(argx<3)
     {
      fclose(fp[argx]);
      printf("fclose(fp[%X]);\n",argx);
      argx++;
     }
    
     return 0;
    }
    
  • Assembly Chaste Lib

    I have created two functions in x86 Assembly Language that allow me to output any zero terminated string or output any integer in any base from 2 to 36. I will show the full source so people can play with it. This uses system calls on Linux so it won’t work on Windows.

    first, the header file “chaste-lib.asm”

    ; This file is where I keep my function definitions.
    ; These are usually my string and integer output routines.
    
    putstring: ; function to print zero terminated string pointed to by register eax
    
    mov edx,eax ; copy eax to edx as well. Now both registers have the address of the main_string
    
    strlen_start: ; this loop finds the lenge of the string as part of the putstring function
    
    cmp [edx],byte 0 ; compare byte at address edx with 0
    jz strlen_end ; if comparison was zero, jump to loop end because we have found the length
    inc edx
    jmp strlen_start
    
    strlen_end:
    sub edx,eax ; edx will now have correct number of bytes when we use it for the system write call
    
    mov ecx,eax ; copy eax to ecx which must contain address of string to write
    mov eax, 4  ; invoke SYS_WRITE (kernel opcode 4)
    ;mov ebx, 1  ; ebx=1 means write to the STDOUT file
    int 80h     ; system call to write the message
    
    ret ; this is the end of the putstring function return to calling location
    
    
    
    
    
    
    radix dd 16 ;radix or base for integer output. 2=binary, 16=hexadecimal, 10=decimal
    
    putint: ; function to output decimal form of whatever integer is in eax
    
    push eax ;save eax on the stack to restore later
    
    mov ebp,int_string+31 ;address of start digits
    
    digits_start:
    
    mov edx,0;
    mov esi,[radix] ;radix is from memory location just before this function
    div esi
    cmp edx,10
    jb decimal_digit
    jge hexadecimal_digit
    
    decimal_digit: ;we go here if it is only a digit 0 to 9
    add edx,'0'
    jmp save_digit
    
    hexadecimal_digit:
    sub edx,10
    add edx,'A'
    
    
    save_digit:
    
    mov [ebp],dl
    cmp eax,0
    jz digits_end
    dec ebp
    jmp digits_start
    
    digits_end:
    
    mov eax,ebp ; now that the digits have been written to the string, display it!
    call putstring
    
    pop eax  ;load eax from the stack so it will be as it was before this function was called
    ret
    

    next, the main source that includes the header: “main.asm”

    format ELF executable
    entry main
    
    include 'chaste-lib.asm'
    
    main: ; the main function of our assembly function, just as if I were writing C.
    
    ; I can load any string address into eax and print it!
    
    mov ebx, 1 ;ebx must be 1 to write to standard output
    
    mov eax,msg
    call putstring
    mov eax,main_string ; move the address of main_string into eax register
    call putstring
    
    mov [radix],2 ; can choose radix for integer output!
    
    mov eax,0
    loop1:
    call putint
    inc eax
    cmp eax,100h;
    jnz loop1
    
    mov eax, 1  ; invoke SYS_EXIT (kernel opcode 1)
    mov ebx, 0  ; return 0 status on exit - 'No Errors'
    int 80h
    
    ; this is where I keep my string variables
    
    msg db 'Hello World!', 0Ah,0     ; assign msg variable with your message string
    main_string db "This is Chastity's Assembly Language counting program!",0Ah,0
    int_string db 32 dup '?',0Ah,0
    
    
    
    ; This Assembly source file has been formatted for the FASM assembler.
    ; The following 3 commands assemble, give executable permissions, and run the program
    ;
    ;	fasm main.asm
    ;	chmod +x main
    ;	./main
    
    

    If you have the fasm compiler, you can assemble this source on any Linux distribution running on an intel CPU. Assembly is platform specific but it runs really fast and the process of programming with it is enjoyable for me.

  • Assembly Language Counting Program

    I have been learning x86 assembly language. I know a little bit from years ago but now it is coming back to me. I formerly did 16 bit DOS hobby programs. This is 32 bit Linux programming in assembly using FASM as my assembler.

    format ELF executable
    entry main
    
    main: ; the main function of our assembly function, just as if I were writing C.
    
    ; I can load any string address into eax and print it!
    
    mov eax,msg
    call putstring
    mov eax,main_string ; move the address of main_string into eax register
    call putstring
    
    
    mov eax,0
    loop1:
    call putint
    inc eax
    cmp eax,16;
    jnz loop1
    
    mov eax, 1  ; invoke SYS_EXIT (kernel opcode 1)
    mov ebx, 0  ; return 0 status on exit - 'No Errors'
    int 80h
    
    ; this is where I keep my string variables
    
    msg: db 'Hello World!', 0Ah,0     ; assign msg variable with your message string
    main_string db 'This is the assembly counting program!',0Ah,0
    int_string db 32 dup '?',0Ah,0
    
    ; this is where I keep my function definitions
    
    putstring: ; function to print zero terminated string pointed to by register eax
    
    mov edx,eax ; copy eax to edx as well. Now both registers have the address of the main_string
    
    strlen_start: ; this loop finds the lenge of the string as part of the putstring function
    
    cmp [edx],byte 0 ; compare byte at address edx with 0
    jz strlen_end ; if comparison was zero, jump to loop end because we have found the length
    inc edx
    jmp strlen_start
    
    strlen_end:
    sub edx,eax ; edx will now have correct number of bytes when we use it for the system write call
    
    mov ecx,eax ; copy eax to ecx which must contain address of string to write
    mov eax, 4  ; invoke SYS_WRITE (kernel opcode 4)
    mov ebx, 1  ; write to the STDOUT file
    int 80h     ; system call to write the message
    
    ret ; this is the end of the putstring function return to calling location
    
    putint: ; function to output decimal form of whatever integer is in eax
    
    push eax ;save eax on the stack to restore later
    
    mov ebx,int_string+31 ;address of start digits
    
    digits_start:
    
    mov edx,0;
    mov esi,10
    div esi
    add edx,'0'
    mov [ebx],dl
    cmp eax,0
    jz digits_end
    dec ebx
    jmp digits_start
    
    digits_end:
    
    mov eax,ebx ; now that the digits have been written to the string, display it!
    call putstring
    
    pop eax  ;load eax from the stack so it will be as it was before this function was called
    ret
    
    ; This Assembly source file has been formatted for the FASM assembler.
    ; The following 3 commands assemble, give executable permissions, and run the program
    ;
    ;	fasm main.asm
    ;	chmod +x main
    ;	./main
    

    This program only works on computers with Intel x86 CPUs and running a Linux distribution. the “int 80h” instructions mean interrupt 128. For some reason, this calls the Linux kernel. I don’t know why it works this way but I do know enough assembly to write my own string and integer routines to replace printf since it is not available in pure assembly like I could in the C programming language.

  • 3 SDL Examples

    This post isn’t Chess related but it is still very nerdy. I have made 3 different SDL programs that all do the exact same thing. However they are written using different SDL versions over time as the API has changed. Therefore, SDL version 1,2, and 3 source code is provided as well as the commands to compile them!

    SDL Version 1

    #include <stdio.h>
    #include <SDL.h>
    int width=1280,height=720;
    int loop=1;
    SDL_Surface *surface;
    SDL_Event e;
    int main(int argc, char **argv)
    {
     if(SDL_Init(SDL_INIT_EVERYTHING)){return 1;}
    
     SDL_putenv("SDL_VIDEO_WINDOW_POS=center");
     SDL_WM_SetCaption("SDL1 Program",NULL);
     surface=SDL_SetVideoMode(width,height,32,SDL_SWSURFACE);
     if(surface==NULL){return 1;}
    
     SDL_FillRect(surface,NULL,0xFF00FF);
    
     while(loop)
     {
      while(SDL_PollEvent(&e))
      {
       if(e.type==SDL_QUIT){loop=0;}
       if(e.type==SDL_KEYUP){if(e.key.keysym.sym==SDLK_ESCAPE){loop=0;}}
      }
      SDL_Flip(surface);
     }
    
     SDL_Quit();
     return 0;    
    }
    
    /*
    SDL1 program that creates a window but nothing else.
    Closes when user presses Esc or clicks the X of the window.
    This is to test whether SDL1 programs can be compiled.
    
     With the sdl-config script:
     gcc -Wall -ansi -pedantic sdl1-test.c -o sdl1-test `sdl-config --cflags --libs` && ./sdl1-test
    
     Without the sdl-config script:
     gcc -Wall -ansi -pedantic sdl1-test.c -o sdl1-test -I/usr/include/SDL -D_GNU_SOURCE=1 -L/usr/lib/x86_64-linux-gnu -lSDL && ./sdl1-test
    */
    

    SDL Version 2

    #include <stdio.h>
    #include <SDL.h>
    int width=1280,height=720;
    int loop=1;
    SDL_Window *window;
    SDL_Surface *surface;
    SDL_Event e;
    int main(int argc, char **argv)
    {
     if(SDL_Init(SDL_INIT_VIDEO))
     {
      printf( "SDL could not initialize! SDL_Error: %s\n",SDL_GetError());return -1;
     }
     window=SDL_CreateWindow("SDL2 Program",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,width,height,SDL_WINDOW_SHOWN );
     if(window==NULL){printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );return -1;}
     surface = SDL_GetWindowSurface( window ); /*get surface for this window*/
     SDL_FillRect(surface,NULL,0xFF00FF);
     SDL_UpdateWindowSurface(window);
     printf("SDL Program Compiled Correctly\n");
     while(loop)
     {
      while(SDL_PollEvent(&e))
      {
       if(e.type == SDL_QUIT){loop=0;}
       if(e.type == SDL_KEYUP)
       {
        if(e.key.keysym.sym==SDLK_ESCAPE){loop=0;}
       }
      }
     }
     SDL_DestroyWindow(window);
     SDL_Quit();
     return 0;
    }
    
    /*
     This source file is an example to be included in Chastity's Code Cookbook. This example follows the SDL version 2 which works differently than the most up to date version (version 3 at this time). There is also an updated version in the same repository that works with version 3.
    
     Linux Compile Command:
    
     With the sdl2-config script:
     gcc -Wall -ansi -pedantic sdl2-test.c -o sdl2-test `sdl2-config --cflags --libs` && ./sdl2-test
    
     Without the sdl2-config script:
     gcc -Wall -ansi -pedantic sdl2-test.c -o sdl2-test -I/usr/include/SDL2 -lSDL2 && ./sdl2-test
    */
    

    SDL Version 3

    #include <stdio.h>
    #include <SDL.h>
    int width=1280,height=720;
    int loop=1;
    SDL_Window *window;
    SDL_Surface *surface;
    SDL_Event e;
    int main(int argc, char **argv)
    {
     if(!SDL_Init(SDL_INIT_VIDEO))
     {
      printf( "SDL could not initialize! SDL_Error: %s\n",SDL_GetError());return -1;
     }
     window=SDL_CreateWindow("SDL3 Program",width,height,0);
     if(window==NULL){printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );return -1;}
     surface = SDL_GetWindowSurface( window ); /*get surface for this window*/
     SDL_FillSurfaceRect(surface,NULL,0xFF00FF);
     SDL_UpdateWindowSurface(window);
     printf("SDL Program Compiled Correctly\n");
     while(loop)
     {
      while(SDL_PollEvent(&e))
      {
       if(e.type == SDL_EVENT_QUIT){loop=0;}
       if(e.type == SDL_EVENT_KEY_UP)
       {
        if(e.key.key==SDLK_ESCAPE){loop=0;}
       }
      }
     }
     SDL_DestroyWindow(window);
     SDL_Quit();
     return 0;
    }
    
    /*
     This source file is an example to be included in Chastity's Code Cookbook. By following the migration guide, I converted the SDL2-test program to the changes in SDL3.
    
     https://wiki.libsdl.org/SDL3/README-migration
    
     Windows Compile Command:
    
     gcc -Wall -ansi -pedantic sdl3-test.c -o sdl3-test -IC:/w64devkit/include/SDL3 -lSDL3 && sdl3-test
    
     Linux Compile Command:
    
     gcc -Wall -ansi -pedantic sdl3-test.c -o sdl3-test -I/usr/include/SDL3 -lSDL3 && ./sdl3-test
    
    */
    

    No matter which of those I compile and run, I get the same result:

    All the programs do is create a window and fill the whole thing with Magenta. It’s not that exciting, but it is pretty, and it shows that all 3 versions of SDL work on my Debian Linux machine.