as everyone knows ,printf It's a convenience 、 intuitive 、 Easy to write 、 Printing functions with variable length parameters , But it has a fatal flaw , The following statement will cause a serious runtime error in the program :

printf("%s", 1);

Then the program interrupts , Programmers wake up late at night by phone …… When the nightmare is interrupted, it falls into another nightmare . After deep research, we found that , Behind the scenes is C The problem of language variable length parameter transfer .

  1. No parameter type passed .

  2. No number of parameters passed .

Of course , stay C Language can still solve this problem , but …… But inevitably lost printf Elegance of .C++ Has it improved ? disappointment ……

until C++ Finally, a new standard of argument parameter transfer is released . from Kenny Kerr(1) and sasha(2) Put forward an idea . stay github in , Found a solution tinyformat(3).

But it's not over , To put tinyformat be used for log4cpp in , For the use of vc2010 Programming project provides a safe and reliable log module . Especially for service programs , Daily use can't stop .

encapsulation log4cpp

log4cpp There's a lot of configuration statements , It's not very convenient to use , reference Lan'Sir(4) The article is encapsulated as follows :

class LogBase
{
private:
static LogBase *m_pInstance;
log4cpp::Category *m_pRoot;
protected:
LogBase()
{
m_pRoot = &log4cpp::Category::getRoot();
m_pRoot->setPriority(log4cpp::Priority::INFO);
}
private:
LogBase& operator=(LogBase&);
LogBase(const LogBase&); public:
~LogBase()
{
if ( m_pRoot != NULL) { delete m_pRoot; m_pRoot = NULL; }
if ( m_pInstance != NULL) { delete m_pInstance; m_pInstance = NULL; }
}
static LogBase* getInstance()
{
if( m_pInstance == NULL) m_pInstance = new LogBase(); return m_pInstance;
}
void log(log4cpp::Priority::Value priority, const std::string& message)
{
if (m_pRoot != NULL) m_pRoot->log(priority, message);
}
}; LogBase* LogBase::m_pInstance = NULL;

Use tinyformat

What is depressing is vs2010 Support C++98 instead of C++11. fortunately tinyformat The author has done some work —— Use macro to define loop settings 1-16 A function of two variables .

// C++98 version
void log_info(const char* s)
{
std::string m = s;
LogBase *pInstance = LogBase::getInstance(); \
if (pInstance != NULL) pInstance->log(log4cpp::Priority::INFO, s); \
}
#define MAKE_LOG_INFO_FUNC(n) \
template<TINYFORMAT_ARGTYPES(n)> \
void log_info(const char* fmt, TINYFORMAT_VARARGS(n)) \
{ \
std::string m = tfm::format(fmt, TINYFORMAT_PASSARGS(n)); \
LogBase *pInstance = LogBase::getInstance(); \
if (pInstance != NULL) pInstance->log(log4cpp::Priority::INFO, m); \
}
TINYFORMAT_FOREACH_ARGNUM(MAKE_LOG_INFO_FUNC)

Now you can have a try :

int _tmain(int argc, _TCHAR* argv[])
{
log_info("hello %s!", 555);
log_info("hello world%s!");
return 0; }

Tips

  1. Use... In your own projects at the same time jsoncpp and log4cpp Of lib

    Compile separately lib when , Need to attribute .C/C++. Code generation . Runtime Unified . For example, they are all set to “ Multithreading /MT” Or both are set to “ Multithreaded debugging /MTD”.

    There are the same function names in different types of runtime , There will be duplicate definitions and definition conflict errors when connecting together .

    For details, please refer to the article :“ About VC link2005 Repeat the definition , Define the error resolution of the conflict ”(5) as well as “ Configure your own OpenGL library ,glew、freeglut Library compilation , Library conflict resolution ( attach OpenGL Demo Program )”(6)

  2. Eliminate warnings : Not found PDB“vc100.pdb”

    compile jsoncpp and log4cpp Of lib when , Part of the debug information is put in vc100.pdb In file . Unable to find when compiling and linking your own project vc100.pdb Warning information of .

    In general , When you debug your own project, you don't track jsoncpp and log4cpp Internal . If you really suspect that they have a problem , They also debug in their own projects . therefore , The simple and reasonable solution is to compile lib when , Turn off debugging information .

    take attribute .C/C++. routine . Debug message format Set to null .

    If you still want to keep it in your own project lib This debugging information , To solve the problem of file name conflict . See “warning LNK4099: Not found PDB”(7)

  3. Eliminate warnings : Unresolved external symbols __imp__WSACleanup

    compile log4cpp Of lib You may use ws2_32.lib. See “ Unresolved external symbols __imp__WSACleanup@”(8).

    In the add header file , Add reference :

#pragma comment(lib,"ws2_32.lib")

Reference link :

  1. Windows with C++ - Using Printf with Modern C++

  2. Compile-Time and Runtime-Safe Replacement for “printf”

  3. https://github.com/c42f/tinyformat

  4. Linux Mixed programming +log4cpp

  5. About VC link2005 Repeat the definition , Define the error resolution of the conflict

  6. Configure your own OpenGL library ,glew、freeglut Library compilation , Library conflict resolution ( attach OpenGL Demo Program )

  7. warning LNK4099: Not found PDB“vc120.pdb”

  8. Unresolved external symbols __imp__WSACleanup@

Get rid of printf More about nightmares

  1. Cocos2d-x 3.x Game development tour

    Cocos2d-x 3.x Game development tour Zhong Dilong Writing    ISBN 978-7-121-24276-2 2014 year 10 Published in pricing :79.00 element 516 page 16 open Summary <Cocos2d-x ...

  2. 《Xenogears》( Different armor ) Implicit prototypes and passwords

    <Xenogears>( Different armor ) Implicit prototypes and passwords X Rainbow press : A kind of high-order element “ Life body ”, because “ accident ” Caught as “ Super energy ”, It's not just “ Unlimited energy ” nothing more ,“ it ” There is a will ! In our eyes , this ...

  3. BZOJ_3362_[Usaco2004 Feb]Navigation Nightmare Navigation nightmare _ Union checking set

    BZOJ_3362_[Usaco2004 Feb]Navigation Nightmare Navigation nightmare _ Union checking set Description      Farmer John has N(2≤N≤40000) A farm , label 1 To N,M( ...

  4. HDU 3085 Nightmare Ⅱ( The nightmare Ⅱ)

    HDU 3085 Nightmare Ⅱ( The nightmare Ⅱ) Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Ja ...

  5. Take the right and check the collection 【bzoj3362】: [Usaco2004 Feb]Navigation Nightmare Navigation nightmare

    [bzoj]3362: [Usaco2004 Feb]Navigation Nightmare Navigation nightmare ​ Farmer John has N(2≤N≤40000) A farm , label 1 To N,M(2≤M≤40000) The different droops of the bars ...

  6. web The spring of the front end or The nightmare

    「 What can wechat application number do 」 In short , WeChat " Applet " Wechat based forms can be provided for developers . Navigation . Map . Development components such as media and location , Let them build a HTML 5 application . At the same time, wechat is also open ...

  7. Get rid of DOM operation , from TodoMVC see angularJS

    replace jQuery? I heard about it a long time ago angularJS The name of , Previous leader I often sigh angularJS How wonderful the design is , It's a pity that we haven't had a chance to know more about , National Day holiday because there is no money to travel , I can get to know him ...

  8. C Language : Operator ,printf,scanf Usage of

    Operator / The result of the operation is related to the data type of the operation object , Both numbers are in, Then quotient is int, Take the whole part : Either or both of the divisor and divisor are floating-point data , The quotient is also floating-point , Don't take out the decimal part :16/5 == 3:16/5.0 ...

  9. printf and scanf

    One printf and scanf(printf and scanf yes c Input and output library functions in language ) printf(” Format control “, Output list ) <1> Format control It includes Format statement (%+ The corresponding format corresponds to the letter ). escape ...

Random recommendation

  1. 【C# Public help 】WinRarHelper Helper classes , Achieve file or folder compression and decompression , Combat dry goods

    Instructions for this document This document uses WinRAR Way to do simple compression and decompression action , Dry only , This compression method is less used in actual projects , I usually use third-party compression dll To achieve , Just like my last compressed blog , What's compressed is zip file htt ...

  2. turn jdk1.5 New characteristics ConcurrentHashMap

    ConcurrentHashMap characteristic : Efficient than Hashtable high , Concurrency is better than hashmap good . Combining the characteristics of both .   Set is the most common data structure in programming . And when it comes to concurrency , Almost always cannot do without the support of advanced data structures such as collections ...

  3. EF framework ~ Add bit operation aggregation method for grouping

    Back to directory We know that Linq The group in groupby You can group one or more fields in a collection , And aggregate one of the attributes , and Linq Provides us with a variety of aggregation methods , from aver,sum,count etc. , And in uncle's authority system ...

  4. php Interview question three ——PHP Language foundation ( Base part )

    3、 ... and .PHP Language foundation 1. strlen( ) And mb_strlen( ) What are the functions of ( Sina Technology Department ) strlen and mb_strlen Are used to get the length of the string . strlen For single byte coded characters only , also ...

  5. Traverse TextBox Control

    foreach (System.Windows.Forms.Control control in this.Controls) { if (control is System.Windows.Form ...

  6. fourteen 、Spring Boot logging SLF4J

    Print content in development , Use System.out.println() and Log4j It should be a well-known method .  In fact, we don't recommend using System.out Because of a lot of use System.out Will increase ...

  7. Joseph POJ - 1012 Joseph Ring recursion

    The question : Joseph ring   Before the beginning k After personal k personal   ask m When it's equal to after k I'll go out first Answer key : Because of the former k It's a place that doesn't move , So just consider whether the position after each recursion is in the front or not k Just one There's recursion ans[i]=(ans[i-1]+m ...

  8. LeetCode - 498. Diagonal Traverse

    Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal ...

  9. CSS Quick start - Practical skills

    1. The overall layout Most of the layouts are made up of three parts ,header.body.footer. Code layout : Write three div <!DOCTYPE html> <html lang="en&q ...

  10. 20、List Methods specific to collections

    List A brief introduction to the special methods in it List In addition to Collection Out of the way , There are also some internal methods , By these means , Developers can operate more easily List Implementation class of interface . package com.monkey1024 ...