Menu
CoddyTech

Headers and Linkage

Lesson 29 of 48 in Coddy's C++ for JavaScript Developers course.

A JavaScript module is a file that the runtime loads, executes once and caches; import or require hands you its exports, and Node can tell whether a file is the entry point with require.main === module. C++ has no module loader at runtime. #include pastes a header's text into the file before compilation, each .cpp file is compiled separately as a translation unit, and the linker then joins the compiled pieces. Headers share declarations; definitions live in one .cpp file, and include guards prevent repetition within one translation unit.

JavaScript

function twice(x) {
  return x * 2;
}
module.exports = { twice };
if (require.main === module) {
  console.log(twice(4));
}

C++

#include <iostream>
#include <string>

// What labels.h would share: a declaration.
namespace labels {
std::string bracket(const std::string& s);
}

int main() {
    std::cout << labels::bracket("ready") << "\n";
}

// What labels.cpp would hold: the definition.
namespace labels {
std::string bracket(const std::string& s) {
    return "[" + s + "]";
}
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: two nonnegative integers, not both zero. Implement greatest common divisor in exercise.cpp with declaration in the header.

Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;std::cout<<gcd(a,b)<<"\n";
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in C++ for JavaScript Developers

Practice on your own: Online C++ compiler