简体   繁体   中英

linux/unix and makefiles

In linux make file:
I want to run the output program only in case of successful compilation.

Is there a way to do this?

Easiest way i can think of looks like this...

run: program_name
        ./program_name

"make run" should fail if program_name isn't there and can't be compiled.

make returns with 0 on success and 2 when a compile fails. I tried the following with bash

make && ./success

where success is the name of the generated binary.
The && guarantees that the second program will only execute if the first runs successful.

Like others have said, use && . For example:

$ make && ./a.out

There are two things that make this work; firstly there is a convention in UNIX that all things that succeed return 0 (including C programs). There's an old joke that helps you remember this "the Roman Empire fell because the Romans didn't have a zero with which to successfully terminate their C programs".

Secondly, && is a "short-circuit" version of Boolean "and". That is, it will evaluate the expression on its left hand side and ONLY if that is 0 will it evaluate the expression on the right hand side. This is also the difference between the Java operators && (short circuit) and & (always evaluates both operands). Many imperative languages contain both sorts of operators, in case there are side effects (eg I/O, variable updates) in the right hand operand of the Boolean expression, in which case you definitely want to evaluate both operands. Some people, however, would say that it's bad style to embed side effects in this manner.

如果您构建的可执行文件名为a.out则可以执行以下操作:

% make && ./a.out

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM