0

In my emacs init file, I have this:

(add-hook 'c++-mode-hook
          (lambda ()
            (set (make-local-variable 'compile-command)
                 (concat "g++ " buffer-file-name))))

Then, say I have a c++ file called: test.cpp. I just need to do M-x compile, Emacs would do : g++ test.cpp automatically.

Now, to run the executable, I would need to do: M-x shell, then ./a.out to run the program.

Is there a way to create a command that tells Emacs to do M-x compile then run the executable?

Additionally, how would one change so that M-x compile will give appropriate executable name? For example, if I have test.cpp, then I want it to do: g++ test.cpp -o test instead.

Please help and thank you

1
  • How about using ...?: (compile "COMMAND && ./a.out") or (compile (concat compile-command " && ./.out"))
    – lawlist
    Commented Aug 11, 2019 at 16:01

2 Answers 2

2

To run a command followed by an executable, the user may wish to use the &&. "&&" is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0).

As such, the O.P. may wish to use either of the following:

(compile "COMMAND && ./a.out")

or

(compile (concat compile-command " && ./.out"))
0

Very few useful C/C++ programs are just one source file. We can give answers to ypur exact question but that will not be of much help to you.

A better way is to use a makefile (or other build system e.g. waf, gradle, scons) this gives the rules to build the executable, how to run it and also you should have tests as well.

When prompted for a command using M-x compile you then use make

e.g.

make test # to run tests

make exe # just build the program

make run # to run executables.

As for the makefile this can be made more complex. Note this example has not been run also all indentation must be tabs. The executable I have named exe rather than a.out

exe: test.cpp 
  gcc -o exe test.c 

run: exe
  ./exe   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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