Consider a C program split into two files: main.c and helper.c. The helper.c file defines a function int add(int a, int b) that returns the sum of two integers. The main.c file calls this function and prints the result.
What will be the output when the program is compiled and run?
/* helper.c */ int add(int a, int b) { return a + b; } /* main.c */ #include <stdio.h> int add(int a, int b); // function prototype int main() { int result = add(3, 4); printf("Result: %d\n", result); return 0; }
Remember that the function add is defined in another file and declared in main.c.
The function add correctly returns the sum of 3 and 4, which is 7. The program prints this value.
Given two files, main.c and math_ops.c. The math_ops.c file defines a function int multiply(int x, int y). The main.c file calls multiply but does not include a header file declaring it.
What is the most likely outcome when compiling and running this program?
/* math_ops.c */ int multiply(int x, int y) { return x * y; } /* main.c */ #include <stdio.h> int main() { int result = multiply(5, 6); printf("Product: %d\n", result); return 0; }
Check if the function multiply is declared before use in main.c.
Without a function prototype or header file, the compiler will warn or error about implicit declaration of multiply.
You have two files: main.c and utils.c. The main.c calls a function void greet() defined in utils.c. You compile with gcc main.c only. What error will you get?
/* utils.c */ #include <stdio.h> void greet() { printf("Hello!\n"); } /* main.c */ void greet(); int main() { greet(); return 0; }
Think about what happens if you compile only one source file but call a function defined in another.
Compiling only main.c does not link utils.c, so the linker cannot find greet.
Which of the following is the correct way to declare a function int compute(int a, int b) defined in another file so it can be used in main.c?
Function declarations should match the function signature exactly.
Option A declares the function with correct return type and parameter types. Option A lacks parameter types, C is old style without parameters, A has wrong return type.
You have a C project with 4 source files: main.c, math.c, io.c, and utils.c. You compile each source file separately into object files and then link them into an executable.
How many object files will you have before linking?
Each source file produces one object file when compiled separately.
Each of the 4 source files compiles into one object file, so total 4 object files before linking.