Podcast
Questions and Answers
When modifying code that uses float
to now use double
for storage, which of the following is most accurate regarding the difference between the two solutions presented in the image?
When modifying code that uses float
to now use double
for storage, which of the following is most accurate regarding the difference between the two solutions presented in the image?
- Solution 2 requires changing multiple lines of code, while Solution 1 only requires changing one line.
- Neither solution requires any changes, as `float` and `double` are interchangeable.
- Solution 1 requires changing multiple lines of code, while Solution 2 only requires changing one line. (correct)
- Both solutions require changing the same number of lines of code.
Which statement best describes how enumerations are represented internally in C and closely related languages?
Which statement best describes how enumerations are represented internally in C and closely related languages?
- Enumerations are represented as floating-point numbers.
- Enumerations are represented as boolean values.
- Enumerations are represented as strings.
- Enumerations are represented as integers. (correct)
Consider the following enumeration: enum Status {PENDING, RUNNING, FAILED = 5, SUCCESS};
. What integer value will be assigned to SUCCESS
?
Consider the following enumeration: enum Status {PENDING, RUNNING, FAILED = 5, SUCCESS};
. What integer value will be assigned to SUCCESS
?
- 7
- 4
- 6 (correct)
- 3
Why is reduced manual memory management beneficial for code maintainability?
Why is reduced manual memory management beneficial for code maintainability?
Which scenario would be most suitable for using an enumeration?
Which scenario would be most suitable for using an enumeration?
What is the consequence of invoking make
without specifying a target in a directory containing both Makefile
and makefile
?
What is the consequence of invoking make
without specifying a target in a directory containing both Makefile
and makefile
?
What is the primary purpose of using macros in a Makefile
?
What is the primary purpose of using macros in a Makefile
?
If you want to examine the commands that make
would execute without actually running them, which flag should you use?
If you want to examine the commands that make
would execute without actually running them, which flag should you use?
How are multi-line commands specified within a Makefile
?
How are multi-line commands specified within a Makefile
?
What is the result if you reference a macro in a Makefile
that has not been defined?
What is the result if you reference a macro in a Makefile
that has not been defined?
Which of the following scenarios best illustrates a potential issue arising from the use of global variables?
Which of the following scenarios best illustrates a potential issue arising from the use of global variables?
Consider a variable x
declared inside a for
loop within a function. What is the scope of x
?
Consider a variable x
declared inside a for
loop within a function. What is the scope of x
?
What is the primary risk associated with returning a pointer to an automatic (local) variable from a function?
What is the primary risk associated with returning a pointer to an automatic (local) variable from a function?
How does using the static
keyword affect a local variable within a function in C?
How does using the static
keyword affect a local variable within a function in C?
In the context of variable scope and storage class, what is the key distinction between them?
In the context of variable scope and storage class, what is the key distinction between them?
Which of the following best describes the role of the C preprocessor?
Which of the following best describes the role of the C preprocessor?
What is the purpose of using include guards (e.g., #ifndef HEADER_H
, #define HEADER_H
, #endif
) in header files?
What is the purpose of using include guards (e.g., #ifndef HEADER_H
, #define HEADER_H
, #endif
) in header files?
What is a primary advantage of using dynamic libraries over static libraries in software development?
What is a primary advantage of using dynamic libraries over static libraries in software development?
When using the #include <file>
directive, where does the compiler primarily search for the specified file?
When using the #include <file>
directive, where does the compiler primarily search for the specified file?
Which file extension is commonly associated with dynamic libraries on Linux systems?
Which file extension is commonly associated with dynamic libraries on Linux systems?
What is the significance of Position Independent Code (PIC) when creating dynamic libraries?
What is the significance of Position Independent Code (PIC) when creating dynamic libraries?
What is the function of a C compiler?
What is the function of a C compiler?
What is the correct way to include a header file named myheader.h
that is located in the same directory as the current source file?
What is the correct way to include a header file named myheader.h
that is located in the same directory as the current source file?
A software development team is deciding between static and dynamic libraries for their project. They anticipate frequent updates to certain library functions. Which type of library would be more suitable and why?
A software development team is deciding between static and dynamic libraries for their project. They anticipate frequent updates to certain library functions. Which type of library would be more suitable and why?
Consider the compilation process: source code -> preprocessor -> compiler -> assembler -> linker. At which stage are .i
files generated?
Consider the compilation process: source code -> preprocessor -> compiler -> assembler -> linker. At which stage are .i
files generated?
A dynamic library libexample.so.2.1
has symbolic links libexample.so.2
and libexample.so
pointing to it. What is the 'real name' of the library?
A dynamic library libexample.so.2.1
has symbolic links libexample.so.2
and libexample.so
pointing to it. What is the 'real name' of the library?
In C/C++, what is the purpose of passing a variable by reference to a function?
In C/C++, what is the purpose of passing a variable by reference to a function?
When should you use the -I
option with a C compiler, and what does it accomplish?
When should you use the -I
option with a C compiler, and what does it accomplish?
Why is it generally discouraged to include the full path to a header file directly in the #include
statement (e.g., #include "/path/to/myheader.h"
)?
Why is it generally discouraged to include the full path to a header file directly in the #include
statement (e.g., #include "/path/to/myheader.h"
)?
You are using Valgrind to debug a C program and it reports a block of memory as 'definitely lost'. What does this indicate?
You are using Valgrind to debug a C program and it reports a block of memory as 'definitely lost'. What does this indicate?
Before using Valgrind to check for memory leaks in a C program, what compiler flag is essential to include during compilation?
Before using Valgrind to check for memory leaks in a C program, what compiler flag is essential to include during compilation?
In C programming, what is the primary effect of using the static
keyword on a global variable within a file?
In C programming, what is the primary effect of using the static
keyword on a global variable within a file?
Which of the following describes the most significant difference between scope and access control?
Which of the following describes the most significant difference between scope and access control?
When should you generally prefer to employ file scope for a function in C?
When should you generally prefer to employ file scope for a function in C?
What is the potential outcome if an external symbol has multiple definitions (extdef) within a linked executable?
What is the potential outcome if an external symbol has multiple definitions (extdef) within a linked executable?
In the context of program scope in C, what is the purpose of an external reference (extref
)?
In the context of program scope in C, what is the purpose of an external reference (extref
)?
Given the principle of defining a symbol in the narrowest scope that works, which of the following scenarios best exemplifies its application?
Given the principle of defining a symbol in the narrowest scope that works, which of the following scenarios best exemplifies its application?
How does Valgrind categorize memory leaks where the pointer to the allocated memory is lost, and that allocated memory is not reachable via any existing pointers?
How does Valgrind categorize memory leaks where the pointer to the allocated memory is lost, and that allocated memory is not reachable via any existing pointers?
What does 'possibly lost' signify when reported by Valgrind in the context of memory management?
What does 'possibly lost' signify when reported by Valgrind in the context of memory management?
In C programming, what is the difference between a declaration and a definition of a variable?
In C programming, what is the difference between a declaration and a definition of a variable?
Why is it generally recommended to avoid using global variables that are accessible program-wide by the end user?
Why is it generally recommended to avoid using global variables that are accessible program-wide by the end user?
Flashcards
Typing just 'make'
Typing just 'make'
Executes the first target in the Makefile. Looks for Makefile or makefile in the current directory.
Typing 'make '
Typing 'make
Builds the specific target you name. For example, 'make myprogram'.
'make clean' target
'make clean' target
A target that performs actions like deleting generated files (executables, object files, etc.).
'make -n'
'make -n'
Signup and view all the flashcards
Makefile Macros
Makefile Macros
Signup and view all the flashcards
Tool Chain
Tool Chain
Signup and view all the flashcards
IDE (Interactive Development Environment)
IDE (Interactive Development Environment)
Signup and view all the flashcards
C Compiler
C Compiler
Signup and view all the flashcards
Intermediate Files
Intermediate Files
Signup and view all the flashcards
C Preprocessor (cpp)
C Preprocessor (cpp)
Signup and view all the flashcards
Preventing Multiple Includes
Preventing Multiple Includes
Signup and view all the flashcards
#include
#include
Signup and view all the flashcards
#include "file"
#include "file"
Signup and view all the flashcards
Memory Allocation Efficiency
Memory Allocation Efficiency
Signup and view all the flashcards
Readability and Memory Management
Readability and Memory Management
Signup and view all the flashcards
What is an Enumeration (Enum)?
What is an Enumeration (Enum)?
Signup and view all the flashcards
Enum Default Values
Enum Default Values
Signup and view all the flashcards
Purpose of Enumerations
Purpose of Enumerations
Signup and view all the flashcards
Function Scope
Function Scope
Signup and view all the flashcards
Block (Local) Scope
Block (Local) Scope
Signup and view all the flashcards
Storage Class
Storage Class
Signup and view all the flashcards
Automatic Storage
Automatic Storage
Signup and view all the flashcards
Static Storage
Static Storage
Signup and view all the flashcards
Static Library
Static Library
Signup and view all the flashcards
Dynamic Library
Dynamic Library
Signup and view all the flashcards
Library Naming Conventions
Library Naming Conventions
Signup and view all the flashcards
Symbolic Links for Libraries
Symbolic Links for Libraries
Signup and view all the flashcards
Valgrind
Valgrind
Signup and view all the flashcards
Modifying Variables in Functions
Modifying Variables in Functions
Signup and view all the flashcards
Allocating Memory within a Function
Allocating Memory within a Function
Signup and view all the flashcards
Definitely Lost Memory (Valgrind)
Definitely Lost Memory (Valgrind)
Signup and view all the flashcards
Definitely Lost Memory
Definitely Lost Memory
Signup and view all the flashcards
Possibly Lost Memory
Possibly Lost Memory
Signup and view all the flashcards
Variable Scope
Variable Scope
Signup and view all the flashcards
Access Control
Access Control
Signup and view all the flashcards
Program Scope
Program Scope
Signup and view all the flashcards
Definition (Symbol)
Definition (Symbol)
Signup and view all the flashcards
Reference (Symbol)
Reference (Symbol)
Signup and view all the flashcards
Declaration (Symbol)
Declaration (Symbol)
Signup and view all the flashcards
File Scope
File Scope
Signup and view all the flashcards
Study Notes
- Tool Chain: Sequence of software tools converting source code to binary.
IDE (Interactive Development Environment)
- Windows: Visual Studio
- MacOS: Xcode
- Multi-Platform: Eclipse, IntelliJ, Codelite, CodeBlocks
Compilers
- C compilers: GNU Compiler Collection (GCC), Clang
Intermediate Files
- Consist of
.i
,.s
, and.o
files
C Preprocessor
- Purpose: Interprets
#directives
in.h
and.c
files before the compiler processes the source code. #include
: Merges header files.#define
: Creates macros, with or without arguments.#ifdef
,#if
,#else
,#endif
: Handles conditional compilation.- Exception:
#pragma
is passed to the compiler and ignored if not recognized. - The C preprocessor is abbreviated as cpp.
Preventing Multiple/Circular Includes
- Best practice
.h
pattern:
#ifndef HEADERNAME_H
#define HEADERNAME_H
...body of .h file...
#endif
- HEADERNAME_H gets defined on the first
#include
and file content is skipped on subsequent includes.
Headers and Paths
#include <file>
: Used for system header files; searches standard system directories.#include "file"
: Used for program header files; searches current and "quote" directories first.- Do not include the path to the file in the
#include
statement. - Include the file itself, e.g.,
#include "Parser.h"
, and let the compiler toolchain handle the paths. - The
-I
option passes a directory containing a header file to the compiler. - Paths for the
-I
option can be relative or absolute, and multiple directories can be included.
Compiler
- Compiles C language source code
.i
files into assembly language.s
. - Diagnoses abuses of language and issues warnings/errors.
- Intermediate
.i
and.s
files are normally deleted after assembly.
Assembler
- Assembles assembly code
.s
from the compiler into object code.o
. - Tool setup is normally transparent.
- There are options for controlling it.
- Assembly statements can be inserted into C programs.
Linker
- Stitches together object files into a single binary program file (executable or library).
- Includes all
.o
files of the user program and referenced system libraries. - Creates static (
.a
,.lib
) or dynamic (.so
,.dll
) libraries inserted in the executable file or linked at runtime. - Undefined reference errors typically arise from the linker being unable to find symbol definitions.
What the Linker Does
- Searches object files for tables of external references (e.g.,
printf
). - Reads libraries to find matching external definitions (e.g.,
printf
function instdio.h
). - Libraries can be static or dynamic.
- Static Linking: Includes definitions (code, global variables) in the program file and resolves references.
- Dynamic Linking: Notes library files; definition is determined at runtime.
Linking and Paths
- The linker automatically links standard C libraries, excluding the math library.
- By default, it searches a limited number of system library directories.
- The
-L
flag explicitly gives the linker additional paths. - The
-l
option provides library names for the linker to link with.
Loader
- Invoked by the command shell or program to execute a program file.
- OS opens a fresh process; loader copies program file segments into memory.
- OS creates a stack and heap, then transfers control to the program's first instruction.
- Errors while loading shared libraries are handled by the loader.
Loader (dlopen)
- Used by programs with dynamically linked libraries.
ld.so
loads these when the program starts.- Referenced calls are fixed up on demand.
dlopen
loads shared object plugins on demand at runtime.
Makefiles
- The
make
utility runs commands from a description file to create executables and perform other tasks. - Tasks include removing files, reporting project status, packaging and installing files, and building libraries.
- The
make
utility is not unique;ant
is a similar utility for Java. Cmake
is an improved make that examines file dependencies.- If files don't exist, it attempts to build them; recompiles if dependent files are newer.
Makefile and Compiler Toolchain
make
utility and compiler toolchain are separate but often used together to automate code building.
Makefile Structure
- Each entry in a makefile has three parts:
- Target: The file to be built.
- Prerequisites: Files that must exist for the target to be built.
- Command Line: Command to build the target using the dependencies.
Invoking Make
- Typing
make
builds the first target in a file namedMakefile
ormakefile
. - Typing
make <target>
builds the specified target.
Other Common Targets
- Targets can be non-files, e.g.,
make clean
to delete*.o
files and the core file.
Checking Commands
- You can view the commands that make would execute using the
-n
flag.
Multiline Command Lines
- Use a semicolon to separate multiple command lines.
libawesome.a: awesome.c
gcc awesome.c -o awesome.o -c; \
ar cr libawesome.a awesome.o
- The backslash indicates continuation to the next line.
Makefile Macros
- Macros avoid repetitive typing in makefiles.
- Defined using the
=
sign, e.g.,LIBS = -L/usr/local/lib -lm -llibname
. - Referenced using
$(LIBS)
or${LIBS}
. - Undefined macros are replaced with a null string.
Predefined Macros
- Macro
CC
is predefined as commandcc
(symbolic link to the default C compiler, usually GNU or LLVM). - Macro
LD
is predetermined as commandld
. - These can be used or replaced. E.g.
CC = gcc
.
Macro Strings and Substitutions
- Allows string substitution in macros, e.g.,
SRCS = a.c b.c c.c
and$(SRCS:.c=.o)
translates toa.o b.o c.o
. $(SRCS:.c=)
translates toa b c
; executable names are derived from source file names.
Suffix Rules
- Tell the system how to compile different types of files.
- By convention
.c
files, andmake
has built-in rules to compile source into executable files. - The
-p
option shows all predefined macros.
Comments
- Start with
#
and continue to the end of the line.
Flags
- Flags control options for the tools and can be controlled using makefiles.
Preprocessor Flags
CPPFLAGS = -I<include_file_dir>
adds to the include paths.-Dsymbol[=value]
is equivalent to#define symbol value
;-DNDEBUG
disables assertions.
Compiler Flags
CFLAGS=
-g
: Save symbols for debugger-On
: Optimization level (0,1,2,3)-Wall -std=c11
: All warnings, C11 standard-fpic
: Position-independent code (for shared object library)-c
: Compile and assemble, but do not link
Linker Flags
- LDFLAGS=
-L<library_dir>
pass a library path to the linker-l<library>
link in library-shared
: Create shared object lib.
-o filename
: Creates an output file with a specific name, instead of the default.
Creating Libraries
- Libraries consist of precompiled functions and data.
Library API
- (Application Programming Interface): Interface for the user of a library.
- It is made of all the public components of your interface – functions, constants, custom types etc.
Library Design
- Programmer decides the functionality of library components, function specifics (arguments, return, errors), and clear naming.
- In C, libraries of functions are created; in OOP languages, libraries of classes are created.
Library Design Public Aspects
- Crucial due to API exposure.
- The decision process for the API is similar to deciding on public methods of a class.
Library Design Private Aspects
- Achieved via information hiding: hiding implementation details from the user.
- C lacks tools for making library internals truly inaccessible.
Libraries in Practice
- System-wide libraries on Linux are in
/lib
and/usr/lib
, and headers are in/usr/include
. - Math library file is
libm.so
, with header filemath.h
(names not necessarily the same).
Static and Dynamic Libraries
- Static Libraries: Library contents copied and stored in the final executable at compile time.
- Dynamic Libraries: Linked at runtime; copy not stored in executable.
- Dynamic libraries, also known as shared libraries, are
.so
in Unix/Linux and.dll
in Windows..
Static Libs
- Pros: Self-contained executable, beginner friendly.
- Cons: Large and inflexible executable, library cannot be updated without recompile.
Dynamic Libs
- Pros: Executable can link to different library versions; executable is not bloated.
- Cons: Single executable is less convenient; requires more experience.
- Dynamic libraries are common in real-world applications.
Naming Libraries
- All names begin with
lib
. - Static libraries end with
.a
. - Dynamic libraries end with
.so
(Linux) or.dll
(Windows);.dylib
possible on macOS. - Shared objects can have version numbers after
.so
:libm.so.3
.
Libraries and Symbolic Links
- Create multiple names for the same library with symbolic links.
- Library itself is called “a”:
liba.so.3.2
may have linksliba.so.3
andliba.so
.
Creating a Dynamic (Shared) Library
- Easy to do with gcc.
- Enable Position Independent Code (PIC) for memory location independence.
- Appropriate compiler/linker arguments:
gcc -c -fpic record.c
: Creates.o
file.gcc -shared -o librecord.so record.o
: Creates.so
file.
Using a Library
- Compile step: Convert source code into object file using
-c
withgcc
. - Link step: Links the library to the program using
-lxyz
(lowercase L followed by library name). - Provide the unique part of the library name (not entire name).
Allocating Memory in a function
- Modify something in a function by passing its address (i.e., a pointer).
- Modify a value in a function by passing it by reference.
- Modifications will only change a copy of the value otherwise.
- The value of a pointer variable p is a memory address. Can be initially null.
Valgrind
- A memory debugging tool that can check for memory leaks and diagnose various other memory errors.
- Need the
-g
compiler flag to use.
Valgrind and Memory Leaks
- Marks memory blocks as four types:
- Definitely lost: Leaking memory.
- Indirectly lost: Pointer-based structure leaking memory (e.g., tree with lost root).
- Possibly lost: Program may be leaking memory due to pointer manipulation.
- Detect uninitialized values and writes to unallocated memory.
Scope
- Region over which you can access a variable by name.
- Defines where a variable is visible.
- Storage class determines symbol lifetime.
- Access control determines who can access a visible symbol.
Scope Vs Access Control
- Java has 4 access levels for methods and variables: private, protected, package level, and public.
- A class variable with class-wide scope is visible to all class/objects, but access control can restrict access.
Scope in C
- No access control, but some control over variable visibility.
Four Types of Scope
- Program scope
- File scope
- Function scope
- Block scope
Scoping Principle
- Always define symbols in the narrowest scope possible.
- This prevents errors and improves security.
Program Scope
- The variable is accessible by all source files that make up the executable like functions and global extern variables.
Program Symbol Concepts
- Definition: Where a named thing lives (memory location).
- Reference: Use of the thing by name (must be resolved to location). Declaration: Informs compiler about a name, compiler verifies reference correctness.
External Symbols
- Program scope symbols are passed to the linker in
.o
files.- External definition: "extdef"
- External reference: “extref"
Externals
- Assembly allows linking of programs via program scope, with each language having its own convention for extdef and extref.
Using Program Scope in C: Function
extdef
: Is a defined function. Definition appears in one.c
file.declaration
: Occurs in multiple.c
files with header files
Using Program Scope in C: Variable
extdef
: definition only appears in one.c
outside any function, may or may not be initializeddeclaration
: appears anywhere in a file, usually in a header file.
Using Program Scope
- Decide when to use program scope.
- Variables should not be globally accessible by users.
- Program scope functions should be part of the program’s public interface.
File Scope
- Variables or functions accessible from declaration point to the end of the file.
- In C, static globals are within a file, not the whole program.
- Static avoids linker inclusion, preventing external status.
Using File Scope
- Sits between private and package level in Java.
- Perfect for internal-use functions or variables.
- File Global variables lead to hard to find errors
Function Scope
- Labels following
goto
have function scope and mean you can jump ahead.
Block(local scope)
- Variables are accessible after the declaration point to the end of the block with is anything in curly braces. This includes params, variables, and loop counters.
- Avoid using the same variable names in overlapping scopes.
Scope Vs Storage Class
- Storage class is where and how long variables are kept.
- Different from scope
- Static affects both storage and scope.
Automatic Storage
- Associated with functions.
- Fresh temporary initialized copy on stack for each call, enabling recursion.
Automatic Storage Warning
- Never return pointers to automatic variables, as they disappear when function returns.
Static Storage
- Only one instance of variable in executable program
- Includes program scope, static file/local variables.
static
restricts variable to file scope and changes local variables from automatic to static storage.
Global/External Storage
- Program Scope variables exist as long as program is running.
Dynamic Storage
- A storage class that create storage temporarily on the heap via malloc calloc and realloc. They must be freed via free. Address of these pointers must be stored. The storage is available until you terminate program.
Problems with Precedence
- Common precedence problems:
*p.f
means*(p.f)
int *ap[]
meansint *(ap[])
- Use parentheses for clarity.
Other Common Constructs
int * fp()
is function returning a pointer to int rather than pointer returning int. Use parentheses.
c = getchar() != EOF
needs Parentheses since comparators are of higher precedence than assignment
Typedefs
- Typedefs are aliases or shorthand notations for existing C types.
- The following declares structure, and typedefs alias
Struct Vec2 {
Float x, y,
}
typedef struct Vec2 Vec2;
Types
- Help to make code more readable
- Offload some of the error checking onto the compiler
- Builds good programming habits that will be useful when using languages with stronger type systems
- Using types correctly also helps you to avoid precision issues
Rules for Using Types
- Always pick the appropriate type for the job and use the narrowest type
- Use the C bool type instead of int is always true or false
Enumerations
- Or enum, is a data type consisting of a finite set of named values.
- The following is the template for using enums
Enum CardSuit {CLUBS, DIAMONDS, HEARTS, SPADES};
- Assigns each enum with unique integer
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.
Related Documents
Description
This quiz covers C/C++ concepts like the difference between float and double, enumeration representation, memory management benefits, appropriate enumeration use cases and Makefile functionalities. Also covers inspecting make commands and multi-line commands in Makefiles. Aimed at evaluating understanding of fundamental programming concepts in C/C++.