1

I have started programming in C++ recently and have been testing using classes. What I have noticed is that if I declare a variable before my methods like:

class Test {
    int value;
public:
    int getValue() const;
};

then the public: is not colorized. But if I don't write the int value; at all, then the public: is colored blue, making it stand out more.

This isn't just an error with public:, its a general rule error because having the following:

class Test {
private:
    int value;
public:
    int getValue() const;
};

will colorized private: but not public:. (Here the line int value; could still be removed and public: would still not be colored differently).

Is there a fix for this that I can put in my $HOME/.emacs?

  • Emacs is telling you that you shouldn't depend on default scope ;). – Meaningful Username Jul 1 '15 at 7:58
1

By default, Emacs opens files ending in .h in C mode. If you would like to open them in C++ (where private and public will be highlighted as keywords), you can add the following to your init file:

(push '("\\.h\\'" . c++-mode) auto-mode-alist)

Or (even better):

(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
  • Do headers for actual C files still work the same with this? – Czipperz Jun 28 '15 at 19:51
  • 1
    No, my answer will make all headers open in C++ mode. Normally, this is fine as C++ is a superset of C. If you would like to have fine-grained control you can, for example, add -*- C++ -*- as a comment at the beginning of the file. This will make Emacs use C++ mode for that particular file. – Lindydancer Jun 29 '15 at 5:25
  • @Lindydancer why use push instead of add-to-list? – PythonNut Jun 29 '15 at 19:42
  • @PythonNut, you're right, add-to-list is the better way to do this -- I've updated the answer. Thanks! – Lindydancer Jun 30 '15 at 18:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.