diff --git a/src/bin/psql/Makefile b/src/bin/psql/Makefile
index 771fd71..e05b1cf 100644
--- a/src/bin/psql/Makefile
+++ b/src/bin/psql/Makefile
@@ -23,7 +23,7 @@ override CPPFLAGS := -I. -I$(srcdir) -I$(libpq_srcdir) -I$(top_srcdir)/src/bin/p
 OBJS=	command.o common.o help.o input.o stringutils.o mainloop.o copy.o \
 	startup.o prompt.o variables.o large_obj.o print.o describe.o \
 	tab-complete.o mbprint.o dumputils.o keywords.o kwlookup.o \
-	sql_help.o \
+	sql_help.o psqlscan.o \
 	$(WIN32RES)
 
 FLEXFLAGS = -Cfe -b -p -p
@@ -46,9 +46,6 @@ sql_help.c: sql_help.h ;
 sql_help.h: create_help.pl $(wildcard $(REFDOCDIR)/*.sgml)
 	$(PERL) $< $(REFDOCDIR) $*
 
-# psqlscan is compiled as part of mainloop
-mainloop.o: psqlscan.c
-
 psqlscan.c: psqlscan.l
 ifdef FLEX
 	$(FLEX) $(FLEXFLAGS) -o'$@' $<
diff --git a/src/bin/psql/mainloop.c b/src/bin/psql/mainloop.c
index 16c65ec..3f55813 100644
--- a/src/bin/psql/mainloop.c
+++ b/src/bin/psql/mainloop.c
@@ -413,13 +413,3 @@ MainLoop(FILE *source)
 
 	return successResult;
 }	/* MainLoop() */
-
-
-/*
- * psqlscan.c is #include'd here instead of being compiled on its own.
- * This is because we need postgres_fe.h to be read before any system
- * include files, else things tend to break on platforms that have
- * multiple infrastructures for stdio.h and so on.	flex is absolutely
- * uncooperative about that, so we can't compile psqlscan.c on its own.
- */
-#include "psqlscan.c"
diff --git a/src/bin/psql/mainloop.h b/src/bin/psql/mainloop.h
index 134987a..1557187 100644
--- a/src/bin/psql/mainloop.h
+++ b/src/bin/psql/mainloop.h
@@ -9,6 +9,7 @@
 #define MAINLOOP_H
 
 #include "postgres_fe.h"
+#include "psqlscan.h"
 
 int			MainLoop(FILE *source);
 
diff --git a/src/bin/psql/psqlscan.l b/src/bin/psql/psqlscan.l
index 1208c8f..069c46f 100644
--- a/src/bin/psql/psqlscan.l
+++ b/src/bin/psql/psqlscan.l
@@ -37,8 +37,17 @@
  *
  *-------------------------------------------------------------------------
  */
+%}
+	/*
+	 * postgres_fe.h must be read before any system include files, else
+	 * things tend to break on platforms that have multiple
+	 * infrastructures for stdio.h and so on.
+	 */
+%top{
 #include "postgres_fe.h"
+}
 
+%{
 #include "psqlscan.h"
 
 #include <ctype.h>

