Ошибка nullptr was not declared in this scope

I am running Eclipse Helios and I have g++-4.6 installed. Hope I am not wrong that g++4.6 implements C++ 11 features. I have created a C++ project which uses the nullptr and auto keywords. The build gives the following errors:-

../{filename}.cpp:13:13: error: ‘nullptr’ was not declared in this scope

../{filename}.cpp:14:2: warning: ‘auto’ will change meaning in C++0x; please remove it [-Wc++0x-compat]

Actually it was building fine until yesterday. I am getting these from nowhere today. Please help me solve this problem.

N.N.'s user avatar

N.N.

8,27812 gold badges54 silver badges94 bronze badges

asked Apr 5, 2012 at 17:45

Higher-Kinded Type's user avatar

3

According to the GCC page for C++11:

To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.

Did you compile with -std=gnu++0x ?

answered Apr 5, 2012 at 17:49

Rob I's user avatar

5

Finally found out what to do. Added the -std=c++0x compiler argument under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. It works now!

But how to add this flag by default for all C++ projects? Anybody?

answered Apr 6, 2012 at 11:12

Higher-Kinded Type's user avatar

4

You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile

g++ -std=c++0x *.cpp -o output

answered Aug 11, 2015 at 11:37

The Beast's user avatar

The BeastThe Beast

1,6192 gold badges29 silver badges42 bronze badges

Is that an actual compiler error or a Code Analysis error? Some times the code analysis can be a bit sketchy and report non-valid errors.

To turn off code analysis for the project, right click on your project in the Project Explorer, click on Properties, then go to the C/C++ General tab, then Code Analysis. Then click on «Use Project Settings» and disable the ones that you do not wish for.

Also, are you sure you are compiling with the C++11 compiler?

answered Apr 5, 2012 at 17:48

josephthomas's user avatar

josephthomasjosephthomas

3,24815 silver badges20 bronze badges

10

Go to Settings -> Compiler…
And add flag to «Have g++ follow the coming C++0x ISO C++ language standard [std=c++0x]

answered Dec 13, 2015 at 0:48

Leon's user avatar

LeonLeon

1472 silver badges7 bronze badges

Trying with a different version of gcc worked for me — gcc 4.9 in my case.

answered Mar 9, 2018 at 11:18

JobJob's user avatar

JobJobJobJob

3,7723 gold badges33 silver badges34 bronze badges

I add the «,-std=c++0x» after «-c -fmessage-length=0″,under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. Dont’t forget to add the comma «,» as the seperator.

answered Jul 9, 2016 at 6:40

qie's user avatar

Студворк — интернет-сервис помощи студентам

Такой вопрос решил немного поэксперименнтировать с кодом.
Когда я компилирую этот код в cpp.sh и gdb online компиляторами ошибок не выдаёт. А вот в terminal выдаёт вот эту ошибку

cpp2.cpp: In function ‘int main()’:
cpp2.cpp:10:10: error: ‘nullptr’ was not declared in this scope
ptra = nullptr;

Решил воспользоваться поиском. Вот ссылка Ошибка компиляции: ‘nullptr’ was not declared in this scope, но там я не смог разобраться, что они делают.

Как мне решить эту проблему?
Чуть не забыл когда nullptr меняю на NULL или 0, проблема исчезает. Почему?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
 
int main()
{
    int *ptra = new int;
        *ptra = 10;
        std::cout << ptra << std::endl;
        delete ptra;
        std::cout << ptra << std::endl;
        ptra = nullptr;
        if (ptra == nullptr) {
            std::cout << ptra << std::endl;
        }
 
    return 0;
}

If you are developing C++ programs, you may come across a common error message that says «nullptr was not declared in this scope.» This error message indicates that the compiler cannot find the definition of the nullptr keyword, which is used to represent a null pointer in C++ programming.

In this guide, we will provide you with a step-by-step solution to fix this error message in your C++ programs.

Step 1: Check your compiler version

Before you begin troubleshooting, it is important to check your compiler version. The nullptr keyword was introduced in C++11, so if you are using an older version of the compiler, you may encounter the «nullptr was not declared in this scope» error.

To check your compiler version, open your terminal or command prompt and enter the following command:

g++ --version

This will display the version of your g++ compiler. If your version is older than 4.6, you should update to a newer version that supports C++11.

If you are using a newer version of the compiler that supports C++11, you may still encounter the «nullptr was not declared in this scope» error if you have not included the  header file in your program.

The  header file contains the definition of the nullptr keyword, so you need to include it in your program. To do this, add the following line at the beginning of your code:

#include <cstddef>

Step 3: Use the nullptr keyword correctly

If you have included the  header file and are still encountering the «nullptr was not declared in this scope» error, you may be using the nullptr keyword incorrectly.

The nullptr keyword is used to represent a null pointer in C++ programming. Here is an example of how to use it correctly:

int* ptr = nullptr;

This creates a pointer named «ptr» that points to no object (i.e., it is a null pointer).

FAQ section

Q1: What is a null pointer in C++ programming?

A null pointer is a pointer that does not point to any object. It is represented by the nullptr keyword in C++ programming.

Q2: Why do I get the «nullptr was not declared in this scope» error?

This error occurs when the compiler cannot find the definition of the nullptr keyword. This can happen if you are using an older version of the compiler that does not support C++11 or if you have not included the  header file in your program.

Q3: Can I use NULL instead of nullptr in C++ programming?

Yes, you can use NULL instead of nullptr in older versions of C++. However, nullptr is preferred in C++11 and newer versions.

Q4: What is the difference between nullptr and NULL?

nullptr is a keyword introduced in C++11 that represents a null pointer. NULL is a preprocessor macro that is used to represent a null pointer in older versions of C++.

Q5: How do I update my g++ compiler to a newer version?

You can update your g++ compiler by downloading and installing the latest version from the official GNU Compiler Collection website. Alternatively, you can use a package manager like apt-get (on Ubuntu) or Homebrew (on macOS) to update your compiler.

  • C++11 nullptr
  • The difference between nullptr and NULL in C++
  • How to update g++ compiler on Ubuntu

Solution:

ENABLE_PRECOMPILED_HEADERS=OFF

System information (version)
  • OpenCV => 3.1
  • Operating System / Platform => Ubuntu 16.04
  • Compiler => c++ (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609

Building Opencv 3.3.1 with QT 5.7, VTK-9.0 produced the following message

Generating perf_precomp.hpp.gch/opencv_perf_dnn_Release.gch
In file included from /usr/local/include/vtk-9.0/vtkObject.h:48:0,
                 from /usr/local/include/vtk-9.0/vtkAlgorithm.h:36,
                 from /usr/local/include/vtk-9.0/vtkPolyDataAlgorithm.h:35,
                 from /usr/local/include/vtk-9.0/vtkAppendPolyData.h:35,
                 from /disk1/packages/opencv-3.3.1/build/modules/viz/precomp.hpp:56:
/usr/local/include/vtk-9.0/vtkWeakPointerBase.h: In constructor ‘vtkWeakPointerBase::vtkWeakPointerBase()’:
/usr/local/include/vtk-9.0/vtkWeakPointerBase.h:39:33: error: ‘nullptr’ was not declared in this scope
   vtkWeakPointerBase() : Object(nullptr) {}

Unfortunately, cmake with

did not remove the errors.

  • Without precompiled header option enabled, the build time was much longer.
  • I think I saw a text about this problem of not applying C++11 to the case of precompiled headers, but cannot find the right link.
  • Anyway, OpenCV with VTK9.0, QT5.7 was built, without ‘nullptr’ error.
fisenkdima

Гость


Хочу использовать в коде ключевое слово nullptr. При компиляции QtCreator выдаёт ругань вида:

предупреждение: identifier ‘nullptr’ will become a keyword in C++0x [-Wc++0x-compat]
ошибка: ‘nullptr’ was not declared in this scope

Я в общем и целом понимаю, что ему не нравится. Я не понимаю, почему. Ведь с Qt 5.0 есть дефолтная поддержка C++11. Или я не прав?
Или проблема в самом gcc ( он, к слову, вот такой вот версии: gcc 4:4.6.1-2ubuntu5 )?


Записан
mutineer

Гость


Ключик для включения нового синтаксиса прописан в .pro ?


Записан
fisenkdima

Гость


Очевидно, нет. Я увидел, что nullptr подсвечен и успокоился. Т.е. QtCreator его по умолчанию знает, а компилятор (или какая сущность ругается на это ключевое слово) — нет?
А что нужно прописать в .pro? Для nullptr в частности и для остальных плюшек C++11 в общем.


Записан
mutineer

Гость


QMAKE_CXXFLAGS += -std=c++0x


Записан
fisenkdima

Гость


Гранд мерси.


Записан
alex312

Хакер
*****
Offline Offline

Сообщений: 606

Просмотр профиля


QMAKE_CXXFLAGS += -std=c++0x

Лучше — CONFIG += c++11


Записан
Alex Custov


Ведь с Qt 5.0 есть дефолтная поддержка C++11. Или я не прав?

Qt — это просто библиотека. Creator использует компилятор, которому нужно указать версию стандарта, как уже показали выше.


Записан

Понравилась статья? Поделить с друзьями:
  • Ошибка nullable object must have a value
  • Ошибка null при получении сертификата
  • Ошибка null при подключении к серверу в майнкрафт
  • Ошибка null при загрузке файла
  • Ошибка not found как решить