0
0
Cprogramming~20 mins

Header files and include directive - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Header Hero
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of program with standard and user header includes
What is the output of this C program?
C
#include <stdio.h>
#include "myheader.h"

int main() {
    printMessage();
    return 0;
}

// Contents of myheader.h
// void printMessage() { printf("Hello from header!\n"); }
ALinker error: undefined reference to printMessage
BCompilation error: function printMessage not declared
CHello from header!\nHello from header!
DHello from header!
Attempts:
2 left
💡 Hint
Remember that function definitions should be in source files, not headers.
Predict Output
intermediate
2:00remaining
Effect of include guards in header files
What will be the output of this program?
C
#include <stdio.h>
#include "guarded.h"
#include "guarded.h"

int main() {
    printf("%d\n", VALUE);
    return 0;
}

// guarded.h content:
// #ifndef GUARDED_H
// #define GUARDED_H
// #define VALUE 10
// #endif
ACompilation error: redefinition of VALUE
B0
CRuntime error
D10
Attempts:
2 left
💡 Hint
Include guards prevent multiple definitions.
🔧 Debug
advanced
2:00remaining
Identify the error with include directive
Why does this code fail to compile?
C
#include <stdio.h>
#include <myheader.h>

int main() {
    printHello();
    return 0;
}

// myheader.h content:
// void printHello() { printf("Hello!\n"); }
ABecause function printHello is not declared before use
BBecause angle brackets <> are used for user headers instead of quotes ""
CBecause function printHello is defined in header, causing multiple definition error
DBecause header file content is commented out
Attempts:
2 left
💡 Hint
Angle brackets are for system headers, quotes for user headers.
Predict Output
advanced
2:00remaining
Output when including header with macro and function
What is the output of this program?
C
#include <stdio.h>
#include "macrofunc.h"

int main() {
    printf("%d\n", SQUARE(5));
    printSquare(5);
    return 0;
}

// macrofunc.h content:
// #define SQUARE(x) ((x)*(x))
// void printSquare(int x) { printf("%d\n", x*x); }
A25\n25
BCompilation error: multiple definitions of printSquare
CRuntime error
D25\n10
Attempts:
2 left
💡 Hint
Macros are replaced by the preprocessor, functions need to be linked properly.
🧠 Conceptual
expert
2:00remaining
Why use include guards or #pragma once?
What is the main reason to use include guards or #pragma once in header files?
ATo allow headers to be included only in main.c file
BTo speed up compilation by skipping system headers
CTo prevent multiple inclusion of the same header causing redefinition errors
DTo automatically link libraries during compilation
Attempts:
2 left
💡 Hint
Think about what happens if a header is included multiple times.