簡體   English   中英

vc140 x64項目缺少c ++ libgen.h(mingw)-幫助器函數

[英]c++ libgen.h (mingw) missing for vc140 x64 project - helper functions

我有以下輔助功能:

std::string
pathname_directory(const std::string &pathname)
{
  char buffer[pathname.size() + 1];
  memset(buffer, 0, sizeof(buffer));
  std::copy(pathname.begin(), pathname.end(), buffer);
  return std::string(dirname(buffer));
}

std::string
pathname_sans_directory(const std::string &pathname)
{
  char buffer[pathname.size() + 1];
  memset(buffer, 0, sizeof(buffer));
  std::copy(pathname.begin(), pathname.end(), buffer);
  return std::string(basename(buffer));
}

它依賴於mingw頭文件libgen.h。

1)為什么在包含“ char buffer [pathname.size()+ 1];”的行中,VS給出錯誤“表達式必須具有恆定值”?

2)是否有用於VS 2015的預定義函數來處理此問題?

libgen.hPosix頭文件 ,因此問題與mingw沒有特別關系。

編譯器抱怨:

char buffer[pathname.size() + 1];

因為標准C ++(任何標准)都禁止使用可變長度數組(盡管C99允許使用它們)。

您可以通過重寫函數來避免使用VLA:

#include <string>
#include <memory>
#include <algorithm>
#include <libgen.h>

std::string
pathname_directory(const std::string &pathname)
{
    char const *cs = pathname.c_str();
    std::size_t cslen = pathname.size() + 1;
    std::unique_ptr<char[]> pbuf(new char[cslen]);
    std::copy(cs,cs + cslen,pbuf.get());
    return dirname(pbuf.get());
}

std::string
pathname_sans_directory(const std::string &pathname)
{
    char const *cs = pathname.c_str();
    std::size_t cslen = pathname.size() + 1;
    std::unique_ptr<char[]> pbuf(new char[cslen]);
    std::copy(cs,cs + cslen,pbuf.get());
    return basename(pbuf.get());
}

但是,從dirnamebasename獲得的幫助可能不值得像這樣(或實際上是您嘗試獲取它的方式)那樣繁瑣。

特別是這樣,如果您想要的pathname_directory(pathname)是所有pathname ,但不包括最后一個路徑分隔符,而您想要的pathname_sans_directory(pathname)是所有pathname在最后一個路徑分隔符之后。 因為dirnamebasename會通過返回“”使您感到驚訝。 如果您希望使用空字符串。 請參閱dirname和基basename文檔。

如果是這樣,那么最少的麻煩便是自己動手做:

#include <string>

std::string
pathname_directory(const std::string &pathname)
{
    std::size_t len = pathname.find_last_of("/\\");
    return len == std::string::npos ? "": pathname.substr(0,len);
}

std::string
pathname_sans_directory(const std::string &pathname)
{
    std::size_t len = pathname.find_last_of("/\\");
    return len == std::string::npos ? pathname : pathname.substr(len + 1);
}

或者您可以在Windows上使用LLVM(clang)進行編譯。 您可以將clang作為C ++下Visual Studio安裝的一部分進行安裝。 Clang允許使用可變長度數組,但MSBuild(Visual Studio中的默認值)不允許。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM