Is there a way to escape macro names (identifiers) in a c pre processor (cpp) ?
I want to conditionalize some web code (html, css...) with readable macro names.
Example for a conditional css file:
/*root*/
some rootcode
#if height==480
/* height 480 */
.page {
line-height:23px;
}
#elif height<480
/* height < 480 */
.page {
line-height:46px;
}
#endif
An invocation of
cpp -P -D height=480 -oout.css css.ccss
results in (after deleting newlines)
some rootcode
.page {
line-480:23px;
}
but "line-480" is wrong.
Is there a way to escape "height" in the code without changing the macro name or stringify it?
You can either:
1) undefine the macro:
#undef height
2) rename the macro using standard-like caps:
#define HEIGHT
3) Use guards before processing the file:
#if height==480
#define HEIGHT_480
#undef height
#endif
#if height>480
#define HEIGHT_OVER_480
#undef height
#endif
/*root*/
some rootcode
#if HEIGHT_480
/* height 480 */
.page {
line-height:23px;
}
#elif HEIGHT_OVER_480
/* height < 480 */
.page {
line-height:46px;
}
#endif
The first one loses information after the undefine. The second one is impractical if there's extensive use of the macro.
The third one is the best option IMO. I've seen it used in production code where stuff like this was necessary.
I played with the idea of Luchian Grigore to undefine used filenames and I found a (nearly) general solution for this problem:
including a "define.file" at the begin of the conditionals and a "undefine.file" after the given condition.
So the problem is reduced to two macro names, that have to stay: DEFINEFILE und UNDEFINEFILE. But this two macros could be encrypted with their hashcode or with a randomname to avoid a use of this names in the conditional text.
The "define.file":
#define height 480
#define os 1
The "undefine.file"
#undef height
#undef os
the "conditionalcss.ccss"
/*root*/
some rootcode
#include __DEFINEFILENAMEPATH__
#if height==480
#include __UNDEFINEFILENAMEPATH__
/* height 480 */
.page {
line-height:23px;
}
#include __DEFINEFILENAMEPATH__
#elif height<480
#include __UNDEFINEFILENAMEPATH__
/* height > 480 */
.page {
line-height:46px;
}
#include __DEFINEFILENAMEPATH__
#endif
#if os==1
#include __UNDEFINEFILENAMEPATH__
os is windows (if 1 refers to windows)
and height also undefined i hope
#endif
Finally the cppcall with the parametric define and undefine files:
cpp -P -D __DEFINEFILENAMEPATH__="\"define.file\"" -D __UNDEFINEFILENAMEPATH__="\"undefine.file\"" -oout.css css.ccss
With this idea, the restulting "out.css" looks like:
some rootcode
.page {
line-height:23px;
}
os is windows (if 1 refers to windows)
and height also undefined i hope
This solution has only the disadvantages of two macros and a possible poor performace because of the multiple imports.
I hope it helps other people to solve their problem.
Greetz
Adreamus
Related
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 3 years ago.
I'm working on an implementation of an EST(Enrollment over Secure Transport)-client over CoAPs for the OpenThread stack. For this, i want to write a CSR (Certificate Signing Request) by using mbedTLS, which is part of the stack as a third party software. My problem now is that i get some "undefined reference" error from the linker when i build the code (i'm using GCC on an Ubuntu 18.04.2 LTS machine).
As there are multiple functions for which the error occurs, i will provide code for just one example. here is my source file:
openthread/src/core/crypto/ecp.cpp:
#include "ecp.hpp"
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/ecp.h>
#include <mbedtls/pk.h>
#include "common/code_utils.hpp"
#include "common/debug.hpp"
#include "common/random.hpp"
#include "openthread/entropy.h"
#include "openthread/random_crypto.h"
namespace ot {
namespace Crypto {
#if OPENTHREAD_ENABLE_EST_CLIENT && OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
otError Ecp::KeyPairGeneration(const uint8_t *aPersonalSeed,
uint32_t aPersonalSeedLength,
uint8_t * aPrivateKey,
uint32_t * aPrivateKeyLength,
uint8_t * aPublicKey,
uint32_t * aPublicKeyLength)
{
otError error = OT_ERROR_NONE;
mbedtls_pk_context keypair;
OT_UNUSED_VARIABLE(aPersonalSeed);
OT_UNUSED_VARIABLE(aPersonalSeedLength);
mbedtls_pk_init(&keypair);
// Generate keypair
VerifyOrExit(mbedtls_pk_setup(&keypair, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)),
error = OT_ERROR_FAILED);
VerifyOrExit(mbedtls_ecp_group_load(&mbedtls_pk_ec(keypair)->grp, MBEDTLS_ECP_DP_SECP256R1) == 0,
error = OT_ERROR_FAILED);
VerifyOrExit(mbedtls_ecp_gen_keypair(&mbedtls_pk_ec(keypair)->grp, &mbedtls_pk_ec(keypair)->d,
&mbedtls_pk_ec(keypair)->Q, mbedtls_ctr_drbg_random,
Random::Crypto::MbedTlsContextGet()) == 0,
error = OT_ERROR_FAILED);
VerifyOrExit(mbedtls_pk_write_pubkey_pem(&keypair, (unsigned char*)aPublicKey,
*aPublicKeyLength) == 0,
error = OT_ERROR_INVALID_ARGS);
VerifyOrExit(mbedtls_pk_write_key_pem(&keypair, (unsigned char*)aPrivateKey,
*aPrivateKeyLength) == 0,
error = OT_ERROR_INVALID_ARGS);
exit:
mbedtls_pk_free(&keypair);
return error;
}
#endif // OPENTHREAD_ENABLE_EST_CLIENT
} // namespace Crypto
} // namespace ot
my header file:
openthread/src/core/crypto/ecp.hpp
#ifndef ECP_HPP_
#define ECP_HPP_
#include "openthread-core-config.h"
#include <stdint.h>
#include <stdlib.h>
#include <openthread/error.h>
namespace ot {
namespace Crypto {
/**
* #addtogroup core-security
*
* #{
*
*/
/**
* This class implements elliptic curve key generation.
*
*/
class Ecp
{
public:
/**
* This method generate a Elliptic Curve key pair.
*
* #param[in] aPersonalSeed An additional seed for the entropy. Can be NULL.
* #param[in] aPersonalSeedLengh The length of the #p aPersonalSeed.
* #param[out] aPrivateKey An output buffer where the private key should be stored.
* #param[inout] aPrivateKeyLength The length of the #p aPrivateKey buffer.
* #param[out] aPublicKey An output buffer where the private key should be stored.
* #param[inout] aPublicKeyLength The length of the #p aPublicKey buffer.
*
* #retval OT_ERROR_NONE EC key pairs has been created successfully.
* OT_ERROR_NO_BUFS Key buffers are too small or mbedtls heap too small.
*/
static otError KeyPairGeneration(const uint8_t *aPersonalSeed,
uint32_t aPersonalSeedLength,
uint8_t * aPrivateKey,
uint32_t * aPrivateKeyLength,
uint8_t * aPublicKey,
uint32_t * aPublicKeyLength);
};
/**
* #}
*
*/
} // namespace Crypto
} // namespace ot
#endif // ECP_HPP_
The functions which cause the error are here mbedtls_pk_write_pubkey_pem and mbedtls_pk_write_key_pem.
Here is also a part of the console output:
Making all in apps
Making all in cli
CC ot_cli_ftd-main.o
CC ot_cli_mtd-main.o
CCLD ot-cli-ftd
CCLD ot-cli-mtd
/opt/gcc-arm-none-eabi-8-2018-q4-major/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/bin/ld: ../../../src/core/libopenthread-mtd.a(libopenthread_mtd_a-ecp.o): in function `ot::Crypto::Ecp::KeyPairGeneration(unsigned char const*, unsigned long, unsigned char*, unsigned long*, unsigned char*, unsigned long*)':
/home/scnm/eclipse-workspace/openthread/examples/../src/core/crypto/ecp.cpp:79: undefined reference to `mbedtls_pk_write_pubkey_pem'
/opt/gcc-arm-none-eabi-8-2018-q4-major/bin/../lib/gcc/arm-none-eabi/8.2.1/../../../../arm-none-eabi/bin/ld: /home/scnm/eclipse-workspace/openthread/examples/../src/core/crypto/ecp.cpp:83: undefined reference to `mbedtls_pk_write_key_pem'
collect2: error: ld returned 1 exit status
Makefile:1249: recipe for target 'ot-cli-mtd' failed
make[5]: *** [ot-cli-mtd] Error 1
I first thougth it was because i was missing some #define to actually use these functions, but i compared it with other OpenThread code which uses mbedtls and i can't see what i did wrong. As far as i've understood it, i have to modify the "openthread/third_party/mbedtls/mbedtls-config.h" file so that these funtions are build, so this is what i did:
#ifndef MBEDTLS_CONFIG_H
#define MBEDTLS_CONFIG_H
#include <stdio.h>
#include <stdlib.h>
#include <openthread/config.h>
#include <openthread/platform/logging.h>
#include <openthread/platform/memory.h>
#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf
#define MBEDTLS_AES_C
#define MBEDTLS_AES_ROM_TABLES
#define MBEDTLS_ASN1_PARSE_C
#define MBEDTLS_ASN1_WRITE_C
#define MBEDTLS_BIGNUM_C
#define MBEDTLS_CCM_C
#define MBEDTLS_CIPHER_C
#define MBEDTLS_CMAC_C
#define MBEDTLS_CTR_DRBG_C
#define MBEDTLS_ECJPAKE_C
#define MBEDTLS_ECP_C
#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
#define MBEDTLS_ECP_NIST_OPTIM
#define MBEDTLS_ENTROPY_C
#define MBEDTLS_HAVE_ASM
#define MBEDTLS_HMAC_DRBG_C
#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
#define MBEDTLS_MD_C
#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
#define MBEDTLS_NO_PLATFORM_ENTROPY
#define MBEDTLS_PK_C
#define MBEDTLS_PK_PARSE_C
#define MBEDTLS_PLATFORM_C
#define MBEDTLS_PLATFORM_MEMORY
#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
#define MBEDTLS_SHA256_C
#define MBEDTLS_SHA256_SMALLER
#define MBEDTLS_SSL_CLI_C
#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
#define MBEDTLS_SSL_EXPORT_KEYS
#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
#define MBEDTLS_SSL_PROTO_TLS1_2
#define MBEDTLS_SSL_PROTO_DTLS
#define MBEDTLS_SSL_TLS_C
#if OPENTHREAD_ENABLE_BORDER_AGENT || OPENTHREAD_ENABLE_COMMISSIONER || OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
#define MBEDTLS_SSL_COOKIE_C
#define MBEDTLS_SSL_SRV_C
#endif
#if OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#if OPENTHREAD_ENABLE_EST_CLIENT
#define MBEDTLS_PEM_WRITE_C
#define MBEDTLS_PK_WRITE_C
#define MBEDTLS_X509_CSR_WRITE_C
#define MBEDTLS_X509_CREATE_C
#endif
#endif
#ifdef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
#define MBEDTLS_BASE64_C
#define MBEDTLS_ECDH_C
#define MBEDTLS_ECDSA_C
#define MBEDTLS_OID_C
#define MBEDTLS_PEM_PARSE_C
#define MBEDTLS_X509_USE_C
#define MBEDTLS_X509_CRT_PARSE_C
#define MBEDTLS_X509_USE_C
#define MBEDTLS_X509_CRT_PARSE_C
#endif
#if OPENTHREAD_ENABLE_ECDSA
#define MBEDTLS_BASE64_C
#define MBEDTLS_ECDH_C
#define MBEDTLS_ECDSA_C
#define MBEDTLS_OID_C
#define MBEDTLS_PEM_PARSE_C
#endif
#define MBEDTLS_MPI_WINDOW_SIZE 1 /**< Maximum windows size used. */
#define MBEDTLS_MPI_MAX_SIZE 32 /**< Maximum number of bytes for usable MPIs. */
#define MBEDTLS_ECP_MAX_BITS 256 /**< Maximum bit size of groups */
#define MBEDTLS_ECP_WINDOW_SIZE 2 /**< Maximum window size used */
#define MBEDTLS_ECP_FIXED_POINT_OPTIM 0 /**< Enable fixed-point speed-up */
#define MBEDTLS_ENTROPY_MAX_SOURCES 1 /**< Maximum number of sources supported */
#if OPENTHREAD_ENABLE_MULTIPLE_INSTANCES
#define MBEDTLS_PLATFORM_STD_CALLOC otPlatCAlloc /**< Default allocator to use, can be undefined */
#define MBEDTLS_PLATFORM_STD_FREE otPlatFree /**< Default free to use, can be undefined */
#else
#define MBEDTLS_MEMORY_BUFFER_ALLOC_C
#endif
#if OPENTHREAD_ENABLE_APPLICATION_COAP_SECURE
#define MBEDTLS_SSL_MAX_CONTENT_LEN 900 /**< Maxium fragment length in bytes */
#else
#define MBEDTLS_SSL_MAX_CONTENT_LEN 768 /**< Maxium fragment length in bytes */
#endif
#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
#if defined(MBEDTLS_USER_CONFIG_FILE)
#include MBEDTLS_USER_CONFIG_FILE
#endif
#if defined(MBEDTLS_ECP_ALT) && !defined(MBEDTLS_ECP_RESTARTABLE)
typedef void mbedtls_ecp_restart_ctx;
#endif
#include "mbedtls/check_config.h"
#endif /* MBEDTLS_CONFIG_H */
It resolved the "not defined in this scope" errors i've had before, but instead i have now the above described errors.
Here is what i've edited in the common-switch file:
openthread/examples/common-switches.mk
ECDSA ?= 0
// my code begin
EST_CLIENT ?= 0
// my code end
JAM_DETECTION ?= 0
ifeq ($(ECDSA),1)
configure_OPTIONS += --enable-ecdsa
endif
// my code begin
ifeq ($(EST_CLIENT),1)
configure_OPTIONS += --enable-est-client --enable-application-coap-secure
endif
// my code end
ifeq ($(JAM_DETECTION),1)
configure_OPTIONS += --enable-jam-detection
endif
and her what i've added to configure:
openthread/configure.ac
#
# EST Client
#
AC_ARG_ENABLE(est_client,
[AS_HELP_STRING([--enable-est-client],[Enable EST client support #<:#default=no#:>#.])],
[
case "${enableval}" in
no|yes)
enable_est_client=${enableval}
;;
*)
AC_MSG_ERROR([Invalid value ${enable_est_client} for --enable-est-client])
;;
esac
],
[enable_est_client=no])
if test "$enable_est_client" = "yes"; then
OPENTHREAD_ENABLE_EST_CLIENT=1
else
OPENTHREAD_ENABLE_EST_CLIENT=0
fi
AC_SUBST(OPENTHREAD_ENABLE_EST_CLIENT)
AM_CONDITIONAL([OPENTHREAD_ENABLE_EST_CLIENT], [test "${enable_est_client}" = "yes"])
AC_DEFINE_UNQUOTED([OPENTHREAD_ENABLE_EST_CLIENT],[${OPENTHREAD_ENABLE_EST_CLIENT}],[Define to 1 if you want to enable EST Client])
OpenThread DNS Client support : ${enable_dns_client}
// my code begin
OpenThread EST Client support : ${enable_est_client}
// my code end
OpenThread SNTP Client support : ${enable_sntp_client}
I've also edited the makefile:
openthread/src/core/Makefile.am
crypto/ecdsa.hpp \
crypto/ecp.hpp \
crypto/hmac_sha256.hpp \
crypto/ecdsa.cpp \
crypto/ecp.cpp \
crypto/hmac_sha256.cpp \
My build command is "make -f examples/Makefile-nrf52840 EST_CLIENT=1".
I think once this problem is solved, i can solve the others by myself as the root of the problem seems to be the same.
Thanks.
You have an error during the link, the symbol mbedtls_pk_write_pubkey_pem is not defined, that means you missed to specify the lib defining it. Looking on the web it seems you need to link with mbedcrypto, so add libmbedcrypto.a or -lmbedcrypto (and may be use the option -L to specify the path)
It seems you also use X509, if you have missing symbols *X509* link with mbedx509, so add libmbedx509.a or -lmbedx509 (and may be use the option -L to specify the path)
The CPP Core Guidelines propose to use Expects(expression) to state preconditions and Ensures(expression) to state postconditions from the GSL in functions.
Example:
int area(int height, int width)
{
Expects(height > 0 && width > 0); // good
if (height <= 0 || width <= 0) my_error(); // obscure
// ...
}
What is the performance impact of these macros?
Is it just as checking the condition with if and then throwing an exception?
Is there a difference between debug and non-debug mode?
I.e. are the macros also active if the app is built as a release?
I ask because I am thinking about using it as a good practice, i.e. try, if there is not a specific reason against it, just stating possible pre/post conditions (assuming it is not sensible to use different types as parameters) using these macros from the GSL.
These macros are defined in the gsl_assert header.
Here's the relevant code:
#define Expects(cond) GSL_CONTRACT_CHECK("Precondition", cond)
#if defined(GSL_THROW_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) \
: gsl::details::throw_exception(gsl::fail_fast( \
"GSL: " type " failure at " __FILE__ ": " GSL_STRINGIFY(__LINE__))))
#elif defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) : gsl::details::terminate())
#elif defined(GSL_UNENFORCED_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) GSL_ASSUME(cond)
#endif // GSL_THROW_ON_CONTRACT_VIOLATION
As you can see, it depends on how you choose to handle contract violations. In the first two cases, you will pay the cost of a branch plus either throwing an exception or calling std::terminate.
In the case that GSL_UNENFORCED_ON_CONTRACT_VIOLATION is defined, the macros will expand to GSL_ASSUME:
//
// GSL_ASSUME(cond)
//
// Tell the optimizer that the predicate cond must hold. It is unspecified
// whether or not cond is actually evaluated.
//
#ifdef _MSC_VER
#define GSL_ASSUME(cond) __assume(cond)
#elif defined(__GNUC__)
#define GSL_ASSUME(cond) ((cond) ? static_cast<void>(0) : __builtin_unreachable())
#else
#define GSL_ASSUME(cond) static_cast<void>((cond) ? 0 : 0)
#endif
In that case, the condition might or might not be evaluated depending on the compiler. It can also make your code faster as the compiler might be able to optimize more aggressively thanks to the assumptions.
There is no deactivation as for an assert, the condition will be tested all the time:
#if defined(__clang__) || defined(__GNUC__)
#define GSL_LIKELY(x) __builtin_expect(!!(x), 1)
#define GSL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define GSL_LIKELY(x) (!!(x))
#define GSL_UNLIKELY(x) (!!(x))
#endif
And then yes, it throws an exception or even terminate depending on your settings:
#if defined(GSL_THROW_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) \
: gsl::details::throw_exception(gsl::fail_fast( \
"GSL: " type " failure at " __FILE__ ": " GSL_STRINGIFY(__LINE__))))
#elif defined(GSL_TERMINATE_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) \
(GSL_LIKELY(cond) ? static_cast<void>(0) : gsl::details::terminate())
#elif defined(GSL_UNENFORCED_ON_CONTRACT_VIOLATION)
#define GSL_CONTRACT_CHECK(type, cond) GSL_ASSUME(cond)
#endif // GSL_THROW_ON_CONTRACT_VIOLATION
If GSL_UNENFORCED_ON_CONTRACT_VIOLATION is set, nothing happens.
I have a feeling that Expects is slightly against the spirit of C++ (as I perceive this spirit) ... Maybe it would really be good if C++ was more mainstream and Java-like but for me its original idea is to provide maximum performance (sometimes at the cost of less safety/more complexity/lower readability). I think we can obtain both goals without sacrifising performance. For me the solution is quite simple - custom assert (cassert) - that is the fast assert that can be switched on or off for release builds.
Sample implementation (Windows only) :
// cassert.h:
#pragma once
// Switch this macro off for maximum performance release builds:
#define __RELEASE_WITH_ASSERTS__
#ifndef cassert
#if defined(_DEBUG) || defined(__RELEASE_WITH_ASSERTS__)
void __cassert(bool val, const char* szFile, int line, const char* szDesc);
#define cassert(a) ((a) ? ((void)1) : __cassert(a, __FILE__, __LINE__, _CRT_STRINGIZE(#a)))
#else
#define cassert(a)
#endif
#endif
// cassert.cpp
#if defined(_DEBUG) || defined(__RELEASE_WITH_ASSERTS__)
void __cassert(bool val, const char* szFile, int line, const char* szDesc)
{
if (!val)
{
std::string sIgnore;
int mode;
#if defined(_DEBUG)
sIgnore = "\n\nIgnore assertion?";
mode = MB_YESNO;
#else
sIgnore = "";
mode = MB_OK;
#endif
char szLine[16];
_itoa(line, szLine, 10);
std::string sAssertion = std::string("Assertion failed in file ") + szFile + " at line " + szLine + "\n" + szDesc;
Log(sAssertion.c_str());
if (MessageBoxA(NULL, (std::string("Assertion failed in file ") + szFile + " at line " + szLine + "\n" + szDesc + sIgnore).c_str(), "Assertion failed", mode | MB_ICONINFORMATION) == IDNO)
_CrtDbgBreak();
}
}
#endif
Such cassert will make even debug builds run much faster because there is no actual call to (c)assert function, if condition is satisfied (and every such call would be quite heavy because of _CRT_STRINGIZE(#a) (condition as a string).
i have a problem with resources in my audio plugin
here is my resource file
// Unique IDs for each image resource.
#define BCKG_ID 101
#define CANT_ID 102
#define COM10_ID 103
#define COM20_ID 104
#define COM40_ID 105
#define COM80_ID 106
#define SAVE_ID 107
#define WAIT_ID 108
#define ONOFFBYPASS_ID 109
#define ONOFFPRESSED_ID 110
// Image resource locations for this plug.
#define BCKG_FN "resources/img/background.png"
#define CANT_FN "resources/img/cant.png"
#define COM10_FN "resources/img/combo10.png"
#define COM20_FN "resources/img/combo20.png"
#define COM40_FN "resources/img/combo40.png"
#define COM80_FN "resources/img/combo80.png"
#define SAVE_FN "resources/img/savwav.png"
#define WAIT_FN "resources/img/waiting.png"
#define ONOFFBYPASS_FN "resources/img/onoff-bypass.png"
#define ONOFFPRESSED_FN "resources/img/onoff-pressed.png"
i have an assert issue : "file not found" when using this code :
IBitmap onoff1 = pGraphics->LoadIBitmap(ONOFFBYPASS_ID, ONOFFBYPASS_FN, 1);
if i use WAIT_ID instead of ONOFFBYPASS_ID, everything works
in debug assert this code raises a flag:
IBitmap IGraphics::LoadIBitmap(int ID, const char* name, int nStates, bool framesAreHoriztonal)
{
LICE_IBitmap* lb = s_bitmapCache.Find(ID);
if (!lb)
{
lb = OSLoadBitmap(ID, name);
#ifndef NDEBUG
bool imgResourceFound = lb;
#endif
assert(imgResourceFound); **//imgResourceFound = false**
s_bitmapCache.Add(lb, ID);
}
return IBitmap(lb, lb->getWidth(), lb->getHeight(), nStates, framesAreHoriztonal);
}
i tried to :
switch ID values (109 <-> 108)
change the names
check 10 times the paths
but nothing works
it doesn't makes sense, especially because i have 2 other audio plugins with the same part of code that are working ok...
sorry can't provide sample code as it would mean installing VST SDK, WDL-OK...so a bit too much i guess.
please help anyway
Jeff
oh i made a noob error: i forget to add
ONOFFBYPASS_ID PNG ONOFFBYPASS_FN
ONOFFPRESSED_ID PNG ONOFFPRESSED_FN
to MyProg.rc
now everything works
Jeff
I would like to be able to switch my feed between an image, a video and a webcam.
Atm i try this:
#define F_WEBCAM
#define F_VIDEO
#define F_IMAGE
#define FEED(F_WEBCAM)
Somewhere else:
#if defined(FEED) && FEED == F_WEBCAM
ofVideoGrabber vidGrabber;
#elif defined(FEED) && FEED == F_VIDEO
ofVideoPlayer vidPlayer;
#elif defined(FEED) && FEED == F_IMAGE
// code for image
#endif
But i get the following error:
Expected value in expression
Is this possible the way i want?
To compare, you need to define your macro constants with values. This will solve your issue:
#define F_WEBCAM 1
#define F_VIDEO 2
#define F_IMAGE 3
#define FEED F_WEBCAM
I'm working on an application that uses an custom, platform-dependent logger. The application defines some printf-style macros:
#define LOG_DEBUG(format, ...) \
logger.log(DEBUG, __FUNCTION__, format, ##__VA_ARGS__)
...
The past few days I've been working on moving the application to use boost.log. The biggest problem I'm having is trying to retain this macro format so that only the logger internals need to be changed, since boost's logging API is implemented in iostream-style, i.e.
BOOST_LOG(logger) << "something";
Is there an easy way to provide a macro that takes printf-style args and prints them to the boost logger without having to use string buffers? (I would think that having to format to a string would be a performance impact)
If not, is there a way to format a string using va_args without having to #ifdef for different platform implementations of formatting functions? (this was the whole point of moving to boost.log in the first place)
Or just use Boost Format to deal with the printf format string. For example,
template<typename Level, typename T1>
inline void log_format(
const Level level,
const char* const fmt,
const T1& t1)
{
BOOST_LOG_SEV(logger::get(), level) << boost::format(fmt) % t1;
}
Creating logger and extending this to handle multiple arguments (most probably with variadic template arguments) is left as an exercise for the reader.
Unfortunately, there are no clean implementations without the #ifdef statement. I know you want to port your existing logging to boost log as-is. That would be an incorrect way of doing things. printf was designed to be used for C, while boost log was designed for C++. So, my suggestion would be to use it the right way. You can make your logging macros painless than what you've shown in your code sample.
Here's my implementation of boost log where instead of having BOOST_LOG(logger) << "something";, I have it as roLOG_INFO << "something";. I believe this example comes from one of boost log's samples.
RoLog.h
#include <boost/logging/format_fwd.hpp>
#include <boost/logging/writer/on_dedicated_thread.hpp>
// Optimize : use a cache string, to make formatting the message faster
BOOST_LOG_FORMAT_MSG( optimize::cache_string_one_str<> )
#ifndef BOOST_LOG_COMPILE_FAST
#include <boost/logging/format.hpp>
#include <boost/logging/writer/ts_write.hpp>
#endif
// Specify your logging class(es)
typedef boost::logging::logger_format_write< > log_type;
// Declare which filters and loggers you'll use
BOOST_DECLARE_LOG_FILTER(roLogFilter, boost::logging::level::holder)
BOOST_DECLARE_LOG(roLog, log_type)
#define roLOG_WHERE_EACH_LINE 0
#if defined(roLOG_WHERE_EACH_LINE) && roLOG_WHERE_EACH_LINE
# define _roLOG_WHERE << roWHERE
#else
# define _roLOG_WHERE
#endif
// Define the macros through which you'll log
#define roLOG_DBG BOOST_LOG_USE_LOG_IF_LEVEL(roLog(), roLogFilter(), debug ) << "[ DEBUG ]:" _roLOG_WHERE
#define roLOG_WARN BOOST_LOG_USE_LOG_IF_LEVEL(roLog(), roLogFilter(), warning) << "[ WARNING ]:" _roLOG_WHERE
#define roLOG_ERR BOOST_LOG_USE_LOG_IF_LEVEL(roLog(), roLogFilter(), error ) << "[ ERROR ]:" _roLOG_WHERE
#define roLOG_CRIT BOOST_LOG_USE_LOG_IF_LEVEL(roLog(), roLogFilter(), fatal ) << "[ CRITICAL]:" _roLOG_WHERE
#define roLOG_INFO BOOST_LOG_USE_LOG_IF_LEVEL(roLog(), roLogFilter(), info )
struct RoLogOptions;
void roInitLogs(const RoLogOptions& options);
RoLog.cpp
#include <Core/RoLog.h>
#include <Core/RoLogOptions.h>
#include <boost/logging/format.hpp>
#include <boost/logging/writer/ts_write.hpp>
using namespace boost::logging;
BOOST_DEFINE_LOG(roLog, log_type)
BOOST_DEFINE_LOG_FILTER(roLogFilter, level::holder)
#define BLOCK(stmts) do{stmts}while(false)
#define CHECK_AND_DO(var,stmt) if (var) stmt
//------------------------------------------------------------------------------
void roInitLogs(const RoLogOptions& options)
{
static bool initialize = true;
if (initialize)
{
// Add formatters and destinations
// That is, how the message is to be formatted...
CHECK_AND_DO(options.printIndex, roLog()->writer().add_formatter(formatter::idx()));
CHECK_AND_DO(options.printTimestamp, roLog()->writer().add_formatter(formatter::time(options.timestampFormat)));
CHECK_AND_DO(options.autoAppendLine, roLog()->writer().add_formatter(formatter::append_newline()));
// ... and where should it be written to
roLog()->writer().add_destination(destination::dbg_window());
CHECK_AND_DO(options.printToStdOut, roLog()->writer().add_destination(destination::cout()));
if (!options.logFile.empty())
{
destination::file_settings settings;
settings.do_append(options.logFileAppendExisting);
roLog()->writer().add_destination(destination::file(options.logFile, settings));
}
CHECK_AND_DO(options.turnOffCache, roLog()->turn_cache_off());
// ... and set the log-level
level::type boost_log_level;
switch(options.logLevel)
{
case eLogLevel_None:
boost_log_level = level::disable_all;
break;
case eLogLevel_All:
boost_log_level = level::enable_all;
break;
case eLogLevel_Debug:
boost_log_level = level::debug;
break;
case eLogLevel_Info:
boost_log_level = level::info;
break;
case eLogLevel_Warning:
boost_log_level = level::warning;
case eLogLevel_Error:
boost_log_level = level::error;
break;
case eLogLevel_Critical:
boost_log_level = level::fatal;
break;
case eLogLevel_Default:
default:
# ifdef _DEBUG
boost_log_level = level::debug;
# else
boost_log_level = level::info;
# endif // _DEBUG
break;
};
roLogFilter()->set_enabled(boost_log_level);
initialize = false;
}
}
DISCLAIMER: I'm not claiming this to be a perfect piece of code. It works for me and I'm happy with it.
Let's say you would still like the option of logging the printf style, then consider the following code:
class LogUtil
{
static void VLogError(const char* format, va_list argList)
{
#ifdef _WIN32
int32 size = _vscprintf(format, argList) + 1;
#else
int32 size = vsnprintf(0, 0, format, argList) + 1;
#endif
if (size > 0)
{
boost::scoped_array<char> formattedString(new char[size]);
vsnprintf(formattedString.get(), size, format, argList);
roLOG_ERR << formattedString.get();
}
}
}
#define roLOGF_ERR(format, ...) LogUtil::VLogError(format, ##__VA_ARGS)
DISCLAIMER: I haven't tested the above code. You might need to tweak it to make it work for you.