简体   繁体   中英

Can you handle compile time errors in c++?

My project has a function that clears the terminal, which is implemented using the curses library. Compiling with the -lcurses flag works fine, but compiling without yeilds

/tmp/cc3T2MVI.o: In function `ClearScreen()':
clear_term.cpp:(.text+0xb): undefined reference to `cur_term'
clear_term.cpp:(.text+0x26): undefined reference to `setupterm'
clear_term.cpp:(.text+0x37): undefined reference to `tigetstr'
clear_term.cpp:(.text+0x3f): undefined reference to `putp'
collect2: ld returned 1 exit status

This is obviously expected because it cant find the library, but because this functionality is supplemental it would be preferable to define ClearScreen() as an empty function than to have compilation fail. I know that I put the function definition in a #ifdef block but I don't know any flags defined by curses.

Is it possible to catch these errors and instead define ClearScreen() as an empty function?

You can define a macro in the Makefile:

use_curses=1
FLAGS+=-DUSING_MAKEFILE
ifeq ($(use_curses),0)
    FLAGS+=-DNO_NCURSES
else
    LIBS+=-lcurses
endif

And in the code:

#ifndef USING_MAKEFILE
#       error "Please use provided Makefile to compile!"
#endif

#ifdef NO_CURSES
        void ClearScreen() { }
#endif

Actually, that is a linker error. And no, it can't really be caught at compile time. But one possibility would be to load the shared object dynamically in ClearScreen . If it failed to load the library, then it could just return. Doing the check at run time may be preferable to build time checks if you are not guaranteed to be building the binary on the target system on which it will ultimately be running.

What you are trying to do (configuring the project with respect to dependencies) — is the classical task of build systems.

For example, with CMake , you'll have FindCurses module, which defines CURSES_FOUND preprocessor variable (if it founds the library).

With GNU Autotools you'll have similar macro, consult the relevant documentation.

If you're using your own build system — then you have to manually code the handling of relevant flags in configuration time.

You really need this library. Maybe it will help you: http://linux.die.net/man/3/tigetstr

Your build script should detect whether a suitable version of curses is present on the build machine. You can generate such script with GNU Autotools for example (the result iwould be a familiar configure script. You can also write a simple custom script in sh / bash .

您尚未考虑的问题是您的代码可能是#include的ncurses.h,如果没有在编译器可以找到它的位置安装库,该代码将永远无法工作。

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