diff --git a/gcc/cp/ChangeLog b/gcc/cp/ChangeLog
index ad765412832fc9bc94c6d771748b73d6c8d20fee..6730b1093788b108f83dac7d5a5c8e0a66fed8e4 100644
--- a/gcc/cp/ChangeLog
+++ b/gcc/cp/ChangeLog
@@ -1,3 +1,9 @@
+2012-10-12  Paolo Carlini  <paolo.carlini@oracle.com>
+
+	PR c++/24449
+	* decl.c (grokfndecl): When checking for ::main declarations
+	use PROCESSING_REAL_TEMPLATE_DECL_P().
+
 2012-10-12  Marc Glisse  <marc.glisse@inria.fr>
 
 	PR c++/53055
diff --git a/gcc/cp/decl.c b/gcc/cp/decl.c
index f97f7b193a0ffe200270529ec84714d8ab7924b4..468343f40a3b033188f22ead82fd701585e85fb9 100644
--- a/gcc/cp/decl.c
+++ b/gcc/cp/decl.c
@@ -7416,7 +7416,7 @@ grokfndecl (tree ctype,
 
   if (ctype == NULL_TREE && DECL_MAIN_P (decl))
     {
-      if (processing_template_decl)
+      if (PROCESSING_REAL_TEMPLATE_DECL_P())
 	error ("cannot declare %<::main%> to be a template");
       if (inlinep)
 	error ("cannot declare %<::main%> to be inline");
diff --git a/gcc/testsuite/ChangeLog b/gcc/testsuite/ChangeLog
index 3b9f121baea2516f7f1798cc98a1ca3331d78f39..862b4273055419a54ac0f02bd37a8d3bc20d3471 100644
--- a/gcc/testsuite/ChangeLog
+++ b/gcc/testsuite/ChangeLog
@@ -1,3 +1,8 @@
+2012-10-12  Paolo Carlini  <paolo.carlini@oracle.com>
+
+	PR c++/24449
+	* g++.dg/parse/friend-main.C: New.
+
 2012-10-12  Marc Glisse  <marc.glisse@inria.fr>
 
 	PR c++/53055
diff --git a/gcc/testsuite/g++.dg/parse/friend-main.C b/gcc/testsuite/g++.dg/parse/friend-main.C
new file mode 100644
index 0000000000000000000000000000000000000000..e6d32e71ba47c958383761f3b0a4ae1ed532673a
--- /dev/null
+++ b/gcc/testsuite/g++.dg/parse/friend-main.C
@@ -0,0 +1,30 @@
+// PR c++/24449
+
+class Fooa
+{
+  friend int main();
+};
+
+template <class T> class Foob
+{
+  friend int main();
+  int i;
+};
+
+int main()
+{
+  Foob<void> a;
+  a.i = 7;
+}
+
+class Fooc
+{
+  template<class T> friend int main(); // { dg-error "cannot declare .::main. to be a template" }
+};
+
+template<class T> class Food
+{
+  template<class U> friend int main(); // { dg-error "cannot declare .::main. to be a template" }
+};
+
+template<class U> int main() {} // { dg-error "cannot declare .::main. to be a template" }