diff --git a/pyopencl/c_wrapper/wrap_cl_core.h b/pyopencl/c_wrapper/wrap_cl_core.h
index 6494a460b41fdf175426d9e022368ae973e4fc89..7069dcbc5695a72f1c85e6a9db83a0c5a9688ae6 100644
--- a/pyopencl/c_wrapper/wrap_cl_core.h
+++ b/pyopencl/c_wrapper/wrap_cl_core.h
@@ -54,6 +54,8 @@ int have_gl();
 
 unsigned bitlog2(unsigned long v);
 void populate_constants(void(*add)(const char*, const char*, long value));
+int get_debug();
+void set_debug(int debug);
 
 // Platform
 error *get_platforms(clobj_t **ptr_platforms, uint32_t *num_platforms);
diff --git a/setup.py b/setup.py
index e2f569020437884f5a3eeeaaaa9cb1083aac6e17..59bf27de7e14ef0d8cb36c6e9e4f1a62c81a0bab 100644
--- a/setup.py
+++ b/setup.py
@@ -249,6 +249,7 @@ def main():
                                 "src/c_wrapper/sampler.cpp",
                                 "src/c_wrapper/program.cpp",
                                 "src/c_wrapper/kernel.cpp",
+                                "src/c_wrapper/debug.cpp",
                                 ],
                                include_dirs=(
                                    conf["CL_INC_DIR"]
diff --git a/src/c_wrapper/debug.cpp b/src/c_wrapper/debug.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1a1b76a15fa95fe56fc9f8f0c5bf9c34f09c267f
--- /dev/null
+++ b/src/c_wrapper/debug.cpp
@@ -0,0 +1,43 @@
+#include "debug.h"
+#include <stdlib.h>
+
+namespace pyopencl {
+
+static PYOPENCL_INLINE bool
+_get_debug_env()
+{
+    const char *env = getenv("PYOPENCL_DEBUG");
+#ifdef PYOPENCL_TRACE
+    const bool default_debug = true;
+#else
+    const bool default_debug = false;
+#endif
+    if (!env) {
+        return default_debug;
+    }
+    if (strcasecmp(env, "0") == 0 || strcasecmp(env, "f") == 0 ||
+        strcasecmp(env, "false") == 0 || strcasecmp(env, "off") == 0) {
+        return false;
+    }
+    if (strcasecmp(env, "1") == 0 || strcasecmp(env, "t") == 0 ||
+        strcasecmp(env, "true") == 0 || strcasecmp(env, "on") == 0) {
+        return true;
+    }
+    return default_debug;
+}
+
+bool debug_enabled = _get_debug_env();
+
+}
+
+int
+get_debug()
+{
+    return (int)pyopencl::debug_enabled;
+}
+
+void
+set_debug(int debug)
+{
+    pyopencl::debug_enabled = (bool)debug;
+}
diff --git a/src/c_wrapper/debug.h b/src/c_wrapper/debug.h
new file mode 100644
index 0000000000000000000000000000000000000000..ba46f7444d49faf4a28b61a0d6d5b1a7d5e48bcc
--- /dev/null
+++ b/src/c_wrapper/debug.h
@@ -0,0 +1,13 @@
+#include "wrap_cl.h"
+#include "utils.h"
+
+#ifndef __PYOPENCL_DEBUG_H
+#define __PYOPENCL_DEBUG_H
+
+namespace pyopencl {
+
+extern bool debug_enabled;
+
+}
+
+#endif