How do I clean a line after using printf with \r in a Makefile

76 Views Asked by At

Let's consider the snippet of a Makefile at the end of this post. It will build object files required to build my program. Every time it builds an object file, it prints : "$(CURSIVE)$(GRAY)- Compiling $(NAME)... $(RST)$@\r" as to display what file is being built, always on the same line.

Then once that is done, it will print "$(CURSIVE)$(GRAY)- Compiling $(NAME)... $(RST)$(GREEN)Done$(RST)\n", on the same line, to indicate that object files have been built.

The issue is that after a \r, the next printf will not necessarily overwrite all the characters that are on the line. So if I printf: "Compiling file10.o\r" then I printf "Compiling file2.o", then on the screen there will be written : "Compiling file2.oo" note the double o.

Until now I would simply add multiple spaces to overwrite any additional characters, but that's not clean, and will not necessarily work perfectly in certain conditions.

Is there a proper way to do that ?

$(NAME): $(OBJ) Makefile
    @printf "$(CURSIVE)$(GRAY)- Compiling $(NAME)... $(RST)$(GREEN)Done$(RST)\n"
    @$(CC) $(LDFLAGS) $(OBJ) -o $(NAME) > /dev/null
    @printf "$(GREEN)- Executable ready.\n$(RST)"

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp | $(BUILD_DIR)
    @printf "$(CURSIVE)$(GRAY)- Compiling $(NAME)... $(RST)$@\r"
    @$(CC) -c $(FLAGS) -I$(INCLUDE_DIR) $< -o $@ > /dev/null
1

There are 1 best solutions below

2
John Bollinger On BEST ANSWER

Until now I would simply add multiple spaces to overwrite any additional characters, but that's not clean, and will not necessarily work perfectly in certain conditions.

Is there a proper way to do that ?

It depends on what you mean by "proper". Personally, I'd consider all the message formatting you're having your recipes do to be slightly improper.

In any case, make recipes consist of shell commands. The shell does not define any standard mechanisms for display control. You are almost completely dependent on the terminal's characteristics for such things. However, I infer from your variable names that you are already using some kind of control codes to modify the the terminal's text colors and typefaces. Most likely, you are using ANSI escape sequences. If so, then ANSI has a clear-to-EOL sequence, <Esc>-K, which would be the natural thing to bring to bear.