Saturday, September 21, 2024

CS50x C code on Windows: Docker, WSL

Excellent course, with code examples in Scratch, C, Python, SQL, web (JS,CSS,HTML), and even "AI"

Why bother learning C, now that we can even use AI to generate code?
Because C is the foundation that all other computing tools are based on!
Understanding the foundations is the best way to learn CS.

CS50x 2024  CS50: Introduction to Computer Science | Harvard University

Harvard University’s introduction to the intellectual enterprises of computer science and the art of programming


For practicing with code examples there is a great online option
of using customize web version of VS Code at //cs50.dev/

It is even better to run on a local computer, with full control.
Running C examples on Windows could be tricky, since usual setup requires whole Visual Studio, i.e. community edition, plus C++ compiler, could be many GBs, and commands a different than on Linux/Unix.

A better alternative is using Docker, or WSL2, that is Linux running on Windows.


WSL2


Then, all examples can use used directly as presented on recorded lectures.
VS Code installed on Windows can share files and command directly with WSL.

Even better alternative may be using Docker, but this requires a bit more effort to setup.

When running C examples that are using shared "cs50" C library, 
here are required command to install and use it

first, need to install clang C/C++ compiler
sudo apt install clang

download cs50.c and cs50.h from

# Compile cs50.c to an object file
clang -c cs50.c -o cs50.o

# Create a static library
ar rcs libcs50.a cs50.o

# create a shared library
clang -shared -o libcs50.so cs50.o

# copy static library to /usr/local/lib
sudo cp libcs50.a /usr/local/lib/

# copy shared library to /usr/local/lib
sudo cp libcs50.so /usr/local/lib/

# update shared libs
sudo ldconfig


make / Makefile

for compiling and linking C code in one step, we can use unix/linux "make" command.
This requires Makefile like this in current directory or in path
note: must use tabs for indentation; no replacing with spaces

# Default target
all: $(TARGET)

CC = clang
CFLAGS = -Wall -Wextra -I/usr/local/include
LDFLAGS = -L/usr/local/lib -lcs50

# Link the target executable
$(TARGET): $(OBJS)
    $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)

# Compile source files to object files
%.o: %.c
    $(CC) $(CFLAGS) -c $< -o $@

# Clean up
clean:
    rm -f $(TARGET) $(OBJS)

as an alternative, can have this Makrfile in parent directory, and in current have Makefile like this

include ../Makefile

then can make (compile and link) and run the program 

make calculator0
./calculator0


Videos

CS50x 2024 - Lecture 1 - C - YouTube (playlist)

CS50 - YouTube


Code

CS50 @GitHub


Download files

all download files CS50 CDN, including ai https://cdn.cs50.net/ai/2023/x/


edX


Docs


No comments: