Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I force a compile error in C++?

I would like to create a compile-time error in my C++ code with a custom error message. I want to do this for a couple of reasons:

  • to force compilation to fail while I'm working on new features which haven't been implemented yet. (compile time ! TODO reminder)
  • to create a more readable error when attempting to implement an unsupported template specialization.

I'm sure there is a trick to doing this but I cant find a resource explaining the method. I would wrap the code in a #define of the form COMPILE_FAIL("error message");

Thanks D

like image 876
Dominic Birmingham Avatar asked Jan 31 '13 19:01

Dominic Birmingham


People also ask

What causes compilation error in C?

Compilation error refers to a state when a compiler fails to compile a piece of computer program source code, either due to errors in the code, or, more unusually, due to errors in the compiler itself. A compilation error message often helps programmers debugging the source code.

What causes a compile error?

A compile error happens when the compiler reports something wrong with your program, and does not produce a machine-language translation. You will get compile errors.

What prevents code from compiling?

Compilers emit both erorrs, which prevent your code from compiling at all, and warnings, which indicate a potential problem, but still let your code compile. (Unless you have ask the compiler to treat warnings as errors, such as with the -Werror flag to gcc).

Which can generate preprocessor error?

The directive ' #error ' causes the preprocessor to report a fatal error. The tokens forming the rest of the line following ' #error ' are used as the error message. The directive ' #warning ' is like ' #error ', but causes the preprocessor to issue a warning and continue preprocessing.


2 Answers

Use #error:

#error "YOUR MESSAGE"

This produces an error from the preprocessor. If you want to detect an error at a later stage (e.g. during template processing), use static_assert (a C++11 feature).

like image 79
nneonneo Avatar answered Sep 19 '22 16:09

nneonneo


Look into static_assert.

Example:

#include <iostream>
#include <type_traits>

template<typename T>
class matrix {
    static_assert(std::is_integral<T>::value, "Can only be integral type");
};

int main() {
    matrix<int*> v; //error: static assertion failed: Can only be integral type
}
like image 41
Rapptz Avatar answered Sep 21 '22 16:09

Rapptz