C++ File Extensions

What's the difference between 'main.cpp' and other file extensions like '.txt'?

File extensions tell both the computer and the programmer what kind of file we're working with. For C++ programs, we typically use .cpp, but there are several related extensions you might encounter:

Common C++ Extensions

  • .cpp - Main C++ source files (most common)
  • .cc - Alternative C++ source extension (common in Linux)
  • .h or .hpp - Header files (we'll learn about these later)
  • .c - C language source files (C++ is based on C)

The main difference is how your computer and IDE treat these files:

// main.cpp - will be compiled as C++
#include <iostream>
using namespace std;

int main() {
  cout << "This is a C++ program!";
}

If we saved the exact same code as main.txt:

  • The IDE won't syntax highlight it properly
  • The compiler won't recognize it as code
  • We can't build and run it directly

Why Extensions Matter

The extension tells your development tools:

  • Which syntax highlighting to use
  • Whether the file should be compiled
  • Which compiler settings to use
  • Which language rules to enforce

For example, saving a C++ file as .c might cause issues:

// main.c - compiler will treat this as C code

// C doesn't have iostream!
#include <iostream>  

int main() {
  // cout doesn't exist in C
  std::cout << "This won't compile as C!";  
}

Different Extensions for Different Tools

Some IDEs create additional files with their own extensions:

  • .sln - Visual Studio solution files
  • .vcxproj - Visual Studio project files
  • .o or .obj - Compiled object files
  • .exe - Windows executable (the final program)

For now, just remember to save your C++ code files with the .cpp extension - this ensures your development environment will treat them properly as C++ source code.

Setting up a C++ Development Environment

Getting our computer set up so we can create and build C++ programs. Then, creating our very first application

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Text Needs Quotes
Why do we need to use double quotes for text but not for numbers?
Program Closes Too Fast
Why does the program window close immediately after running?
Forgetting Semicolons
What happens if I forget to put a semicolon at the end of a line?
Understanding std:: Prefix
Why do some code examples online use std::cout instead of just cout?
Understanding namespace std
Why do we need to write using namespace std; - what happens if we remove it?
Cross-Platform Code
How do I make my program work on both Windows and Mac without changing the code?
Compiling vs Running
What's the difference between compiling and running a program?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant