Ambiguous pointer; <SiHCollection> is ambiguous - c++

below I've posted my code which is meant to store hits collections in HCE (hit collection of events).
The code compiles successfully but on running the program, the following error is printed to the terminal seven times:
< SiHCollection> is ambiguous.
I have a feeling it is because I am using namespace std although I don't know how to amend the code. Any thoughts?
#include "SiSD.h"
#include "SiHit.h"
#include "G4HCofThisEvent.hh"
#include "G4Step.hh"
#include "G4ThreeVector.hh"
#include "G4SDManager.hh"
#include "G4ios.hh"
#include "G4UnitsTable.hh"
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
extern ofstream outfile;
SiSD::SiSD(G4String name)
:G4VSensitiveDetector(name)
{
collectionName.insert("SiHCollection");
}
SiSD::~SiSD(){ }
void SiSD::Initialize(G4HCofThisEvent* HCE)
{
SiHCollection = new SiHitsCollection(SensitiveDetectorName,
collectionName[0]);
static G4int HCID = -1;
if(HCID<0)
{
HCID = G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
}
HCE->AddHitsCollection(HCID, SiHCollection);
}
G4bool SiSD::ProcessHits(G4Step* aStep, G4TouchableHistory*)
{
if(aStep->GetTrack()->GetTrackID() > 0) {
G4double edep = aStep->GetTotalEnergyDeposit();
if(edep==0) return false;
SiHit* aHit = new SiHit();
aHit->SetEdep(edep);
SiHCollection->insert(aHit);
return true;
} else return false;
}

Related

gRPC keeps returning error code 12 from server

I need to implement a distributed database and I implemented based on gRPC example. The following is my code snippet.
sundial_sync_server.h
#ifndef SUNDIAL_GRPC_SYNC_SERVER_H
#define SUNDIAL_GRPC_SYNC_SERVER_H
#endif //SUNDIAL_GRPC_SYNC_SERVER_H
#include "sundial_grpc.grpc.pb.h"
#include "sundial_grpc.pb.h"
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
using grpc::Channel;
using grpc::ServerContext;
using grpc::Status;
using sundial_rpc::SundialRequest;
using sundial_rpc::SundialResponse;
using sundial_rpc::Sundial_GRPC_SYNC;
#ifndef ABC
#define ABC
class SundialServiceImp final : public Sundial_GRPC_SYNC::Service
{
public:
Status contactRemote(::grpc::ServerContext* context, const ::sundial_rpc::SundialRequest* request, ::sundial_rpc::SundialResponse* response) override;
void run();
};
#endif
sundial_sync_server.cpp
#include "sundial_grpc.grpc.pb.h"
#include "sundial_grpc.pb.h"
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "txn.h"
#include "global.h"
#include "manager.h"
#include "stats.h"
#include "helper.h"
#include "grpc_sync_server.h"
#include "txn_table.h"
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
using grpc::ServerContext;
using grpc::Status;
using sundial_rpc::SundialRequest;
using sundial_rpc::SundialResponse;
using sundial_rpc::Sundial_GRPC_SYNC;
using grpc::Server;
using grpc::ServerBuilder;
Status SundialServiceImp::contactRemote(::grpc::ServerContext* context, const ::sundial_rpc::SundialRequest* request, ::sundial_rpc::SundialResponse* response){
if (request->request_type() == SundialRequest::SYS_REQ) {
glob_manager->receive_sync_request();
response->set_response_type( SundialResponse::SYS_RESP );
return Status::OK;
}
uint64_t txn_id = request->txn_id();
TxnManager * txn_man = txn_table->get_txn(txn_id);
// If no TxnManager exists for the requesting transaction, create one.
if (txn_man == NULL) {
//printf("adding txnID=%ld into txn_table\n", txn_id);
assert( request->request_type() == SundialRequest::READ_REQ );
txn_man = new TxnManager();
txn_man->set_txn_id( txn_id );
txn_table->add_txn( txn_man );
}
// the transaction handles the RPC call
txn_man->process_remote_request(request, response);
// if the sub-transaction is no longer required, remove from txn_table
if (response->response_type() == SundialResponse::RESP_ABORT
|| response->response_type() == SundialResponse::PREPARED_OK_RO
|| response->response_type() == SundialResponse::PREPARED_ABORT
|| response->response_type() == SundialResponse::ACK) {
txn_table->remove_txn( txn_man );
delete txn_man;
}
return Status::OK;
}
void SundialServiceImp::run(){
std::istringstream in(ifconfig_string);
string line;
uint32_t num_nodes = 0;
string port;
while (getline (in, line)) {
if (line[0] == '#')
continue;
else {
if (num_nodes == g_node_id) {
port = line.substr(0, line.length());
break;
}
num_nodes ++;
}
}
port.append(sync_port);
grpc::EnableDefaultHealthCheckService(true);
grpc::reflection::InitProtoReflectionServerBuilderPlugin();
ServerBuilder builder;
builder.AddListeningPort(port, grpc::InsecureServerCredentials());
builder.RegisterService(this);
std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << port << std::endl;
server->Wait();
}
`sundial_sync_client.h'
#endif //SUNDIAL_GRPC_CLIENT_H
#include "sundial_grpc.grpc.pb.h"
#include "sundial_grpc.pb.h"
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using sundial_rpc::SundialRequest;
using sundial_rpc::SundialResponse;
using sundial_rpc::Sundial_GRPC_SYNC;
//toDo: now assume we only have 2 nodes
#ifndef SSC
#define SSC
class Sundial_Sync_Client{
public:
Sundial_Sync_Client(std::shared_ptr<Channel>* channel);
Status contactRemote(uint64_t node_id,SundialRequest& request, SundialResponse* response);
private:
std::unique_ptr<Sundial_GRPC_SYNC::Stub> stub_;
};
#endif
sundial_sync_client.cpp
#include "sundial_grpc.grpc.pb.h"
#include "sundial_grpc.pb.h"
#include "grpc_sync_client.h"
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/grpcpp.h>
#include "txn.h"
#include "global.h"
#include "helper.h"
#include "manager.h"
#include "stats.h"
using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using sundial_rpc::SundialRequest;
using sundial_rpc::SundialResponse;
using sundial_rpc::Sundial_GRPC_SYNC;
//toDo: add more nodes to it
Sundial_Sync_Client::Sundial_Sync_Client(std::shared_ptr<Channel>* channel){
for(int i=0; i<g_num_nodes;i++){
if(i==g_node_id)
continue;
//stub_[i]=Sundial_GRPC_SYNC::NewStub(channel[i]);
stub_=Sundial_GRPC_SYNC::NewStub(channel[i]);
}
}
Status
Sundial_Sync_Client::contactRemote(uint64_t node_id, SundialRequest& request, SundialResponse* response){
//toDo: choose the right stub with node id
ClientContext context;
printf("Client sends request\n");
//Status status = stub_[node_id]->contactRemote(&context, request, &response);
Status status = stub_->contactRemote(&context, request, response);
if (status.ok()) {
//printf("status ok\n");
glob_stats->_stats[GET_THD_ID]->_resp_msg_count[ response->response_type() ] ++;
glob_stats->_stats[GET_THD_ID]->_resp_msg_size[ response->response_type() ] += response->SpaceUsedLong();
return status;
} else {
std::cout << status.error_code() << ": " << status.error_message()
<< std::endl;
return status;
}
}
It runs pretty smoothly at the setup. I did get the ip address and let servers run at the right address. However, when I make the client send request, the status it returns always has error code 12 without error message.
Error code 12 is "UNIMPLEMENTED". Check your proto and make sure your server is implementing the correct RPC method (correct upper/lower case for method name and things like that)

C++ regex cstring error

I wrote this code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <regex>
using namespace std;
int compile()
{
string linecode;
linecode = "_hello:";
if (std::regex_match (linecode, std::regex("(_)(.*)(:)") ))
{
cout<<"...";
}
else if (std::regex_match (linecode, std::regex("(#)(.*)(:)") ))
{
cout<<"###";
}
return 1;
}
int main(int argc, char** argv)
{
compile();
return 0;
}
And i get this error:
enter image description here
cstring error, probably in regex library.
How i can fix this ?
Thanks in advance.

c++ put functions in separate source files

Currently I have an unique source file (*.cpp) where all my functions are working right. Now i'm trying to take some of them out into separate source files and including them into main source with no success.
My current project is as follows:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
using namespace std;
using std::cout;
using std::ifstream;
/*This is one of the functions to be put in separate file:*/
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15;
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre);
if (inputFile.is_open())
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End of function 'ReadPageAsignations'
/*This is another function where my function "ReadPageAsignations' get called -- btw, I want also this function to be in a separate source file.*/
void DeliverHtml (const char* page){//const char* RutayNombre ) {
string *p;
char * pch;
size_t pos;
string RutayNombre;
RutayNombre = "../Substructure/Templates/" + SearchConfigValue( "../Substructure/Conf/Config-Templates.txt", "htmlTemplate:");
const char *RutayNombreConfigCompos = "../Substructure/Conf/Config-Composition.txt";
string RutayNombreParaInsertar;
string token, token1, token2;
string line, lineRead, lineToInsert;
char * StrToTokenize2;
string StrToTokenize1;
p=ReadPageAsignations( RutayNombreConfigCompos, page); //Here, I call the function I want in a separate file
...
}
/*And here is the main() function*/
int main()
{
char *value = "page=Home";
if (NULL!=strstr(getenv("QUERY_STRING"), "page="))
{
value = getenv("QUERY_STRING");
}
char *posCh = strstr(value, "=");
DeliverHtml(&posCh[0]+1);
return 0;
}
For the first function, I have tried creating the header file 'ReadPageAsignations.h' and a source file 'ReadPageAsignations.cpp'.
Header file 'ReadPageAsignations.h' containing:
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
Source file 'ReadPageAsignations.cpp' for separate function containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
using std::cout;
using std::ifstream;
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
bool MisionCumplida = false;
bool EncabezadoListo = false;
int i = 0;
int j = 0;
char * pch;
char istr[256];
const int NUM_DATA = 15; /*El numero de elementos debe coincidir con el iterador en la función Deliverhtml.*/
static string data[NUM_DATA];
std::stringstream InputString;
ifstream inputFile(RutayNombre); //Abre el archivo y lo asigna al stream inputFile.
if (inputFile.is_open()) //Chequea que el archivo esté abierto.
{
while (inputFile.good() && MisionCumplida == false)
{
i = 0;
inputFile.getline(istr,256);
pch = strtok (istr,":");
if (string(pch) == "[Pagina]")
{
EncabezadoListo = true;
}
else
{
EncabezadoListo = false;
}
if (string(pch) == Page)
{
MisionCumplida = true;
}
while (pch != NULL)
{
if ((EncabezadoListo == true) || (MisionCumplida == true))
{
data[i] = data[i] + " " + string(pch);
}
pch = strtok (NULL, ",");
i++;
}
}
inputFile.close();
return data;
}
} //End function
and, main project containing:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h" //Here I #include the function definition file (header)
using namespace std;
using std::cout;
using std::ifstream;
...
}
I've got a lot of compiling errors:
\ReadPageAsignations.h|4|error C2143: syntax error : missing ';' before '*'|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
\ReadPageAsignations.h|4|error C4430: missing type specifier - int assumed. Note: C++ does not support default-int|
main.cpp|20|error C2872: 'string' : ambiguous symbol|
...
I'm working Code::blocks 13.12 with MS Visual C++ 2005/2008 compiler.
any help will be highly appreciated, thanks in advance.
The error is telling you that when it tried to parse the header file it encountered the symbol string and doesn't recognize it. Adding #include <string> to your header file and fully qualifying the string type as std::string should correct the problem.
You should put #include <string> in your header file and remove it from your .cpp file
as following:
main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <windows.h>
#define _SQLNCLI_ODBC_
#include <sqlext.h>
#include <sqlncli.h>
#include "ReadPageAsignations.h"
...
note: including header file with the same name of .cpp file , include both.
ReadPageAsignations.h
#ifndef READPAGEASIGNATIONS_H_INCLUDED
#define READPAGEASIGNATIONS_H_INCLUDED
#include <string> //<-----This line, include string header
std::string *ReadPageAsignations ( const char* RutayNombre, const char* Page );
#endif // READPAGEASSIGNATIONS_H_INCLUDED
ReadPageAsignations.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include "ReadPageAsignations.h" // <--- add the header file here
//#include <string> <---remove it already included in the header file
using namespace std;
//using std::cout; <--remove this you already used namespace std
//using std::ifstream; <--remove this you already used namespace std
string *ReadPageAsignations ( const char* RutayNombre, const char* Page )
{
... } //End function

failing to parse C++ using llvm and clang

I'm writing a little tool with llvm to parse C and C++ code, but I can't seem to get it to successfully parse C++ at all. I'm probably missing something obvious.
This is what I have so far:
#include <iostream>
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/LangStandard.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Parse/ParseAST.h"
class MyASTConsumer : public clang::ASTConsumer {
public:
bool HandleTopLevelDecl(clang::DeclGroupRef d);
virtual ~MyASTConsumer() { }
};
bool MyASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d)
{
for(auto ii = d.begin(); ii != d.end(); ii++)
{
printf("decl type: %s\n", (*ii)->getDeclKindName());
auto namedDecl = llvm::dyn_cast<clang::NamedDecl>(*ii);
if(namedDecl)
{
printf("name: %s\n", namedDecl->getName().data());
}
}
return true;
}
int main(int, char **argv)
{
using clang::CompilerInstance;
using clang::TargetOptions;
using clang::TargetInfo;
using clang::FileEntry;
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
using clang::SrcMgr::CharacteristicKind;
using clang::StringRef;
using clang::DirectoryLookup;
using llvm::MemoryBuffer;
using clang::LangOptions;
using clang::FrontendOptions;
using clang::LangStandard;
using clang::CompilerInvocation;
using clang::InitializePreprocessor;
using clang::Preprocessor;
using clang::PreprocessorOptions;
using clang::HeaderSearch;
using clang::HeaderSearchOptions;
CompilerInstance ci;
DiagnosticOptions diagnosticOptions;
ci.createDiagnostics();
CompilerInvocation *invocation = new CompilerInvocation;
LangOptions &langOpts = ci.getLangOpts();
langOpts.RTTI = 1;
langOpts.Bool = 1;
langOpts.CPlusPlus11 = 1;
langOpts.GNUKeywords = 1;
langOpts.CXXExceptions = 1;
langOpts.POSIXThreads = 1;
langOpts.SpellChecking = 1;
invocation->setLangDefaults(langOpts, clang::IK_CXX, LangStandard::lang_gnucxx11);
ci.setInvocation(invocation);
llvm::IntrusiveRefCntPtr<TargetOptions> pto( new TargetOptions() );
pto->Triple = llvm::sys::getDefaultTargetTriple();
llvm::IntrusiveRefCntPtr<TargetInfo> pti(TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto.getPtr()));
ci.setTarget(pti.getPtr());
ci.createFileManager();
auto &fileManager = ci.getFileManager();
ci.createSourceManager(fileManager);
llvm::IntrusiveRefCntPtr<HeaderSearchOptions> headerSearchOpts( new HeaderSearchOptions() );
ci.createPreprocessor();
auto &pp = ci.getPreprocessor();
pp.setPredefines(builtinMacros);
HeaderSearch &headerSearch = pp.getHeaderSearchInfo();
for(auto &inc: builtinIncludePaths)
{
auto dirEntry = fileManager.getDirectory(StringRef(inc), true);
DirectoryLookup dirLookup(dirEntry, CharacteristicKind::C_System, false);
headerSearch.AddSearchPath (dirLookup, true);
}
MyASTConsumer *astConsumer = new MyASTConsumer();
ci.setASTConsumer(astConsumer);
ci.createASTContext();
const FileEntry *pFile = fileManager.getFile(argv[1]);
auto &sourceManager = ci.getSourceManager();
sourceManager.createMainFileID(pFile);
ci.getDiagnosticClient().BeginSourceFile(
ci.getLangOpts(),
&pp
);
clang::ParseAST(pp, astConsumer, ci.getASTContext());
ci.getDiagnosticClient().EndSourceFile();
return 0;
}
It does parse C just fine, but it errors out on the namespace keyword and extern "C" { blocks. So far I'm stumped. If anyone has a clue, something I'm missing, please share.
I believe I figured out the problem. You should always call setInvocation on the compiler instance before calling a lot of the methods on the compiler instance, as it actually just proxies to the invocation.
I moved the setInvocation call to right after the CompilerInvocation object is created, and things now work.

segfault at the end of the main()

I am compiling a program agains LLVM-CLANG. This is the main
#include <iostream>
#include "CompilerFactory.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/Diagnostic.h"
int main(int argc, char const *argv[])
{
using clang::CompilerInstance;
using clang::TargetOptions;
using clang::TargetInfo;
using clang::FileEntry;
using clang::Token;
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
CompilerInstance ci;
CSFV::CompilerFactory::GetCompilerInstance(ci);
const FileEntry *pFile = ci.getFileManager().getFile("test.c");
ci.getSourceManager().createMainFileID(pFile);
ci.getPreprocessor().EnterMainSourceFile();
ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(),
&ci.getPreprocessor());
Token tok;
do
{
ci.getPreprocessor().Lex(tok);
if (ci.getDiagnostics().hasErrorOccurred())
break;
ci.getPreprocessor().DumpToken(tok);
std::cerr << std::endl;
} while (tok.isNot(clang::tok::eof));
ci.getDiagnosticClient().EndSourceFile();
return 0;
}
and this is the included class
//If they are not defined we have an error at compile time
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#include "llvm/Support/Host.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;
namespace CSFV{
class CompilerFactory
{
public:
CompilerFactory();
~CompilerFactory();
/// \brief Generate and returns a compiler instance object
static void GetCompilerInstance(CompilerInstance &ci){
DiagnosticOptions diagOpts;
TextDiagnosticPrinter* diagPrinter =
new TextDiagnosticPrinter(llvm::outs(), &diagOpts, true);
ci.createDiagnostics(diagPrinter);
llvm::IntrusiveRefCntPtr<TargetOptions> pto (new TargetOptions());
pto->Triple = llvm::sys::getDefaultTargetTriple();
TargetInfo *pti =
TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto.getPtr());
ci.setTarget(pti);
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
ci.createPreprocessor();
return;
}
};
} //end of namespace CSFV
For some reason I get a segfault at the end of the execution of the main. What am I missing?
I don't know if this is the same problem I had, but what I did was declare the targetoptions as a new pointer.
eg:
clang::TargetOptions *targetOpts=new clang::TargetOptions;
I have a feeling targetinfo cleans it up when itself is destroyed.