# C++: error: 'x' was not declared in this scope (undeclared identifier)

**Code:** `was not declared in this scope` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

The compiler met a name it has never seen: it is misspelled, declared later, out of scope, or its header or namespace is missing.

## Meaning

C++ reads a file top to bottom, so a name must be declared before it is used. The usual causes are a missing `#include`, a missing `std::` prefix, a typo (case matters), or using a variable outside the block where it was declared. GCC's message ends with a "suggested alternative" when it finds a close match.

## Common causes

- Missing `#include` for the function or type (for example `<vector>`, `<cstring>`)
- Missing `std::` or `using namespace std`
- Typo or wrong capitalisation in the name
- Variable declared inside a block and used outside it
- Function used before its declaration or prototype

## Quick fix

1. Read GCC's "suggested alternative" hint
2. Include the right header and qualify the name (`std::string`)
3. Declare or prototype the function above its first use

## Detailed fix by platform

### GCC / Clang

1. Find which header declares it: `man 3 strlen` or search cppreference.com for the name
2. Add the header at the top of the file, not just in another .cpp

### C++

1. Prefer `std::` qualification in headers; reserve `using namespace std;` for small programs

## Code examples

### Missing header and std:: prefix

```cpp
#include <iostream>

int main() {
    vector<int> v{1, 2, 3};          // error: 'vector' was not declared in this scope
    cout << v.size() << "\n";         // error: 'cout' was not declared in this scope
}

// Fix:
// #include <vector>
// std::vector<int> v{1, 2, 3};
// std::cout << v.size() << "\n";
```

## How to diagnose

1. **Name** — Spelling and case exactly right?
2. **Header** — Is the declaring header included in THIS file?
3. **Scope** — Is the name used inside the block where it was declared?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/not-declared-in-this-scope)
