Given two C files linked together, what is the output when the program runs?
/* file1.c */ #include <stdio.h> void greet(); int main() { greet(); return 0; } /* file2.c */ #include <stdio.h> void greet() { printf("Hello from file2!\n"); }
Remember that functions declared in one file can be defined in another and linked together.
The function greet() is declared in file1.c and defined in file2.c. When linked, the program calls the correct function and prints the message.
Consider two C files sharing a global variable. What is the value printed?
/* file1.c */ #include <stdio.h> extern int counter; int main() { counter = 5; print_counter(); return 0; } /* file2.c */ #include <stdio.h> int counter = 0; void print_counter() { printf("Counter: %d\n", counter); }
Global variables declared with extern in one file and defined in another share the same memory.
The variable counter is defined in file2.c and declared as extern in file1.c. Setting it to 5 in main changes the shared variable, so print_counter() prints 5.
Why does this program fail to link?
/* file1.c */ #include <stdio.h> void print_message(); int main() { print_message(); return 0; } /* file2.c */ #include <stdio.h> static void print_message() { printf("Hello from file2!\n"); }
Think about the meaning of static for functions in C files.
The static keyword limits the function's visibility to its own file. So print_message in file2.c is not visible to file1.c. The linker cannot find the function definition, causing an undefined reference error.
Which option correctly declares a function defined in another file to avoid linking errors?
/* file1.c */ #include <stdio.h> // Function declaration here int main() { display(); return 0; } /* file2.c */ #include <stdio.h> void display() { printf("Display function called\n"); }
Consider how to tell the compiler the function exists elsewhere.
Using extern void display(); explicitly declares the function is defined in another file. While void display(); and void display(void); are valid declarations, extern clarifies linkage. static would restrict visibility to the current file, causing linking errors.
Given three C files below, how many functions are visible to main() after linking?
/* file1.c */ #include <stdio.h> void funcA(); int main() { funcA(); funcB(); funcC(); return 0; } /* file2.c */ #include <stdio.h> void funcA() { printf("Function A\n"); } static void funcB() { printf("Function B\n"); } /* file3.c */ #include <stdio.h> void funcC() { printf("Function C\n"); }
Remember that static functions are only visible inside their own file.
funcA and funcC are visible to main() because they are non-static and defined in other files. funcB is static in file2.c, so it is not visible outside that file. Therefore, only 2 functions are visible to main().