C++ linker presentation

This commit is contained in:
2026-02-24 10:21:15 +01:00
parent 0fda0d75fb
commit 6f3d98f388
32 changed files with 788 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
#include <iostream>
#include "shared.h"
void print_a() {
std::cout << "a: globalVar = " << globalVar << "\n";
}

View File

@@ -0,0 +1,6 @@
#include <iostream>
#include "shared.h"
void print_b() {
std::cout << "b: globalVar = " << globalVar << "\n";
}

View File

@@ -0,0 +1,10 @@
#!/bin/bash
echo "=== This build SHOULD fail with 'multiple definition' ==="
echo ""
g++ -std=c++17 a.cpp b.cpp main.cpp -o app 2>&1 || true
echo ""
echo "Both a.o and b.o define globalVar because shared.h has a definition."
echo ""
echo "Fix 1: use 'extern int globalVar;' in header, define in one .cpp"
echo "Fix 2: use 'inline int globalVar = 42;' (C++17)"

View File

@@ -0,0 +1,8 @@
void print_a();
void print_b();
int main() {
print_a();
print_b();
return 0;
}

View File

@@ -0,0 +1,13 @@
#pragma once
// BUG: this is a definition, not just a declaration.
// Including this header in multiple TUs causes "multiple definition" errors.
int globalVar = 42;
// FIX (pick one):
// 1. Use extern in header + define in one .cpp:
// extern int globalVar; // in header
// int globalVar = 42; // in one .cpp
//
// 2. Use inline (C++17):
// inline int globalVar = 42;

View File

@@ -0,0 +1,8 @@
#!/bin/bash
echo "=== This build SHOULD fail with 'undefined reference' ==="
echo ""
g++ -std=c++17 main.cpp -o app 2>&1 || true
echo ""
echo "The linker cannot find a definition for add(int, int)."
echo "Fix: provide the .cpp that defines it, or link the correct library."

View File

@@ -0,0 +1,8 @@
#include <iostream>
int add(int, int); // declared but never defined
int main() {
std::cout << add(3, 4) << "\n";
return 0;
}